JAVA对TXT文件的读写操作的工具类


  • JAVA对TXT文件的读写操作的工具类

package com.shop.dome.utils;

import java.io.*;

public class util {
    /**
     * 读取txt文件
     *
     * @param file 要读取文件路径。例:D://test.txt
     * @return
     */
    public static String readFile(String file) {
        String conx = "";
        try {
            FileReader reader = new FileReader(file);
            // 读取到缓冲区
            BufferedReader br = new BufferedReader(reader);
            String line;
            // 一次读入一行数据
            while ((line = br.readLine()) != null) {
                conx += line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return conx;
    }

    /**
     * 写入txt文件
     *
     * @param file 要写入文件路径。例:D://test.txt
     * @param conx 写入内容
     */
    public static void writeFile(String file, String conx) {
        try {
            File writeName = new File(file);
            // 创建新文件,同名的文件会被覆盖
            writeName.createNewFile();
            FileWriter writer = new FileWriter(writeName);
            BufferedWriter out = new BufferedWriter(writer);
            // 缓存区内容写入内容
            out.write(conx);
            // 把缓存区内容写入文件
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM