Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedWriter class writeLine method

Tags:

java

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

like image 917
0ne_Up Avatar asked Dec 15 '15 15:12

0ne_Up


2 Answers

Reading through javadocs I do not see any specific reason why a writeLine() method is not provided. With the provided write methods BufferedWriter will buffer the characters before writing for efficiency purposes. 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 PrintWriter class instead of BufferedWriter as it provides println(String str) method which can be used write a string and a newline character. But this is inefficient when compared to BufferedWriter and it is better to use this only when you want your output file to have the strings written immediately on calling the println() method.

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

To leverage the benefits of BufferedWriter and to have access to println() method, you can do the below as suggested in javadocs:

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
out.println("Hello World!");
like image 152
vk239 Avatar answered Oct 23 '22 21:10

vk239


From https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html

A newLine() method is provided, which uses the platform's own notion of line separator as defined by the system property line.separator. Not all platforms use the newline character ('\n') to terminate lines. Calling this method to terminate each output line is therefore preferred to writing a newline character directly.

like image 3
Max Dribinsky Avatar answered Oct 23 '22 22:10

Max Dribinsky