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()
.
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!");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With