The writeLine method of the BufferedWriter class

Why does the BufferedReader class have a readLine() method, but the BufferedWriter class does not have a writeLine(String) method? Now we have to do write(str + "\n") or write(str) and newLine() .

+5
source share
1 answer

Reading through javadocs I see no specific reason why the writeLine() method is not provided. Using the provided methods, write BufferedWriter will buffer characters before writing to improve performance. Providing a new writeLine() method will not add any value, since the character stream provided in this imaginary writeLine method will be buffered and written only when the buffer is full.

You can switch to the PrintWriter class instead of the BufferedWriter, because it provides a println(String str) method that you can use to write a string and a new character string. But this is inefficient compared to BufferedWriter, and it is better to use it only when you want your output file to have lines written immediately when the println () method is called.

With the BufferedWriter class, for the reason mentioned here, the best approach is to use the write() and newLine() methods.

To take advantage of BufferedWriter and have access to the println() method, you can do the following, as suggested in javadocs :

 PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out"))); out.println("Hello World!"); 
+8
source

Source: https://habr.com/ru/post/1238285/


All Articles