Java method to write the document row

Verbatim https://www.dazhuanlan.com/2019/08/25/5d622ab9a21fa/


This article summarizes the actions related to the use of the class to write a document

1. FileOutputStream

1
2
3
4
5
6
7
8
9
10
public static void writeFile1() throws IOException {
File fout = new File("out.txt");
FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(fos));
for(int i = 0; i < 10; i++) {
br.write("test");
br.newLine();
}
br.close();
}

This example used a FileOutputStream, you can use PrintWriter FileWriter or instead of the operation process txt document format

2. FileWriter

1
2
3
4
5
6
7
public static void () throws IOException {
FileWriter fw = new FileWriter("out.txt");
for(int i = 0; i < 10; i++) {
fw.write("something");
}
fw.close();
}

3. PrintWriter

1
2
3
4
5
6
7
8
public static void writeFile3() throws IOException {
PrintWriter pw = new PrintWriter(new FileWriter("out.txt"));
for(int i = 0; i < 10; i++) {
pw.write("something");
}
pw.close();

}

4. OutputStreamWriter

1
2
3
4
5
6
7
8
9
public static void writeFile4() throws IOException {
File fout = new File("out.txt");
FileOutputStream fos = new FileOutputStream(fout);
OutputStreamWriter osw = new OutputStreamWriter(fos);
for(int i = 0; i < 10; i++) {
osw.write("something");
}
osw.close();
}

The difference between them

From Java Doc

The main difference is that, PrintWriter provide some additional methods and formats such as println printf. In addition, FileWriter throws an exception to prevent any kind of I / O failure.
PrintWriter does not throw IOException, which may be provided using a type checkerror boolean flag bit obtained in (). PrintWriter automatically calls flush after each data byte is written. It involves FileWriter, the caller needs to pay attention to the use of flush.

Description link

Guess you like

Origin www.cnblogs.com/petewell/p/11408044.html