java io写入行数据到文件的几种方法

Java 2019-12-22 阅读 55 评论 0

本文总结了Java可用于写文件的类。Jdk7以上,可以使用 System.lineSeparator() 获取换行字符。在UNIX系统上,返回\n;在Windows系统上,返回 \r\n

1. FileOutputStream

public static void writeFile1() throws IOException {
    File fileOut = new File("out.txt");
    FileOutputStream fos = new FileOutputStream(fileOut);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
    for (int i = 0; i < 10; i++) {
        bw.write("something");
        bw.newLine();
    }
    bw.close();
}

2. FileWriter

public static void writeFile2() throws IOException {
    String newLine = System.lineSeparator();
    FileWriter fw = new FileWriter("out.txt");
//        FileWriter fw = new FileWriter("out.txt", true); // 如果是追加文本,可以使用这行
    for (int i = 0; i < 10; i++) {
        fw.write("something");
        fw.write(newLine);
    }
    fw.close();
}

3. PrintWriter

public static void writeFile3() throws IOException {
    String newLine = System.lineSeparator();
    PrintWriter pw = new PrintWriter(new FileWriter("out.txt"));
    for (int i = 0; i < 10; i++) {
        pw.write("something");
        pw.write(newLine);
    }
    pw.close();
}

4. OutputStreamWriter

public static void writeFile4() throws IOException {
    String newLine = System.lineSeparator();
    File fileOut = new File("out.txt");
    FileOutputStream fos = new FileOutputStream(fileOut);
    OutputStreamWriter osw = new OutputStreamWriter(fos);
    for (int i = 0; i < 10; i++) {
        osw.write("something");
        osw.write(newLine);
    }
    osw.close();
}

不同之处

如果要将文本输出到文件,最好使用Writer类而不是OutputStream类,因为Writer类的目的是处理文本内容。

FileWriter和PrintWriter的官网文档:

FileWriter is a convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

PrintWriter prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.

主要的区别在于PrintWriter提供了一些额外的格式化方法,比如println和printf。此外,FileWriter在任何处理I/O失败的情况下都会抛出IOException。PrintWriter方法不会抛出IOException,而是设置一个boolean标志,该标志可以使用checkError()获得。PrintWriter在写入每个字节的数据后自动调用flush。对于FileWriter的使用,必须注意要调用flush。

最后更新 2020-03-08