Java BufferedWriter 类的 writeLine 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34292661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:30:50  来源:igfitidea点击:

BufferedWriter class writeLine method

java

提问by 0ne_Up

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

为什么BufferedReader类有readLine()方法,而BufferedWriter类没有writeLine(String)方法?现在我们必须做write(str + "\n")orwrite(str)newLine()

采纳答案by vk239

Reading through javadocs I do not see any specific reason why a writeLine()method is not provided. With the provided writemethods 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 writeLinemethod will be buffered and written only when the buffer is full.

通读 javadocs 我没有看到writeLine()未提供方法的任何具体原因。使用提供的write方法 BufferedWriter 将在写入之前缓冲字符以提高效率。提供一个新writeLine()方法不会增加任何值,因为这个虚构writeLine方法中提供的字符流只有在缓冲区满时才会被缓冲和写入。

You can switch to PrintWriterclass 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.

您可以切换到PrintWriter类而不是 BufferedWriter ,因为它提供了println(String str)可用于写入字符串和换行符的方法。但是,与 BufferedWriter 相比,这是低效的,最好仅当您希望输出文件在调用 println() 方法时立即写入字符串时才使用它。

With BufferedWriterclass for the reason mentioned in herebest approach is to use write()and newLine()methods.

由于这里BufferedWriter提到的原因,最好的方法是使用类和方法。write()newLine()

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

要利用方法的好处BufferedWriter并访问println()方法,您可以按照javadocs 中的建议执行以下操作:

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

回答by Max Dribinsky

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

来自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.

提供了一个 newLine() 方法,它使用平台自己的由系统属性 line.separator 定义的行分隔符概念。并非所有平台都使用换行符 ('\n') 来终止行。因此,调用此方法来终止每个输出行比直接写入换行符更可取。