Java读写txt文件

Java读写txt文件

读文件

// 读取文件内容  参数要完成路径和文件名 String filePathName="D:/test/tgj/test1.txt";
private static List<String> ReadFileCon(String filePathName){
    List<String> strList = new ArrayList<>();
    BufferedReader reader;
    try {
        reader = new BufferedReader(new FileReader(filePathName));
        String line = reader.readLine();
        while (line != null) {
            strList.add(line);
            line = reader.readLine();// 继续读取下一行
        }
        reader.close();
        return strList;
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("文件不存在");
        return strList;
    }
}

如果想直接输出,将代码 strList.add(line); 换成 System.out.println(line); 就行。
方法加个返回值,可方便后续对内容的操作
调用

public static void main(String[] args) {
    List<String> list = ReadFileCon("F:\img\test1_r.txt");
    for (String str: list) {
        System.out.println(str);
        System.out.println("-------------------------");
    }
}

需要引入maven包

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;

private static void readTxtFileByFileUtils(String fileName) {
    File file = new File(fileName);
    try {
        LineIterator lineIterator = FileUtils.lineIterator(file, "UTF-8");
        while (lineIterator.hasNext()) {
            String line = lineIterator.nextLine();
            System.out.println(line);
        }
    } catch (IOException e) {
        logger.error(e.getMessage());
    }
}

写文件

// 给指定文件写入内容。若没有就创建,但不能创建目录。String filePathName="D:/test/tgj/test2.txt";
private static void WriteFileCon(String filePathName, String[] str){
    try (FileWriter fw = new FileWriter(filePathName);
         BufferedWriter info = new BufferedWriter(fw))
    {
        for (int i=0; i<str.length; i++) {
            info.write(String.format(str[i] + "%n")); // 加个 %n 相当于换行
        }
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("写入失败");
    }
}

调用

public static void main(String[] args) {
    String[] as = {"熊大", "狗二", "张三", "李四", "王五"};
    WriteFileCon("F:/img/test2_w.txt", as);
}

方法中可以换成传字符串,那整个for循环就能替换成 info.write(str); 调用时就像下面这样

public static void main(String[] args) {

    StringBuilder str = new StringBuilder();
    String data1 = "0056b587dfb4901371a09a59a05f10c1";
    String data2 = "j23434sdfjjur3247834jhk9eqdf574e";
    String data3 = "erigueugd23948924njhsjahf958345j";
    str.append(data1);
    str.append(System.getProperty("line.separator")); // 效果相当于换行
    str.append(data2);
    str.append(System.getProperty("line.separator"));
    str.append(data3);
    str.append(System.getProperty("line.separator"));
    
    WriteFileCon("F:/img/test3_w.txt", str.toString());

}