How does BufferedWriter use the write method to implement line wrapping

  • 2021-11-02 00:46:13
  • OfStack

BufferedWriter write method for line wrapping

The BufferedWriter object comes with the newline () method to wrap lines, but what if you wrap lines in the middle of a string and don't want to use the newline () method?

It is impossible to use\ n. After using\ n, only 1 space will appear, and no line break will be realized. Just add\ r\ n where you want to realize line break.

For example, the following


File file=new File("d:/ioPractice/text.txt");
Writer fw=
new FileWriter(file,true);
BufferedWriter bw=new BufferedWriter(fw);
String str=" This is the first 1 Row \r\n This is the first 2 Row ";

bw.write(str);
bw.flush();
 
bw.close();
fw.close();

Trap for Java output file to wrap through BufferedWriter. newline () method

Recently, the project needs to export files. In fact, exporting files is a very simple thing. But I encountered a very strange problem.

BufferedWriter is required to export to a file first. The line break is through the bw. newline () method, and the problem will be with the newline () method.

Let's look at 1 newline () api:

newLine
public void newLine()
throws IOException
Writes a line separator. The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\n') character.
Throws:
IOException - If an I/O error occurs

English itself should not have any difficulty, meaning: newLine method will call the system line break. And this is the root of the problem.

Line breaks for different systems:

windows -- > \r\n

linux -- > \r

mac -- > \n

Our 1 development is under windows, while Server 1 is under linux.

If we use the newline function to wrap lines, in the native test, because it is an windows environment, the newline character is\ r\ n, and the natural file is wrap processing when opening the file, so there is no problem.

When we deploy to the server, the server is linux environment, newline reads the system newline character is\ r, exports to the file, the newline character of the file is\ r, when we download this file to windows through the browser, there will be no newline problem when we open the file again. Because the interpretation of\ r under windows is not a newline character.

Therefore, we cannot use the newline method if we need to specify that the file wraps in some places during development. You must specify the newline character manually:\ r\ n because looking at the newline characters for the different systems listed above, if the string ends with\ r\ n in three systems, looking at the file will interpret it as a newline.

At this point, the problem analysis is finished.


Related articles: