Java:BufferedWriter 跳过换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4066958/
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
Java: BufferedWriter skipping newline
提问by devnull
I am using the following function to write a string to a File. The string is formatted with newline characters.
我正在使用以下函数将字符串写入文件。该字符串使用换行符进行格式化。
For example, text = "sometext\nsomemoretext\nlastword";
例如, text = "sometext\nsomemoretext\nlastword";
I am able to see the newline characters of the output file when I do:
当我这样做时,我能够看到输出文件的换行符:
type outputfile.txt
However, when I open the text in notepad I can't see the newlines. Everything shows up in a single line.
但是,当我在记事本中打开文本时,我看不到换行符。一切都显示在一行中。
Why does this happen. How can I make sure that I write the text properly to be able to see correctly (formatted) in notepad.
为什么会发生这种情况。如何确保我正确书写文本以便能够在记事本中正确查看(格式化)。
private static void FlushText(String text, File file)
{
Writer writer = null;
try
{
writer = new BufferedWriter(new FileWriter(file));
writer.write(text);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (writer != null)
{
writer.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
回答by Ani
On windows, new-lines are represented, by convention, as a carriage-return followed by a line-feed (CR + LF), i.e. \r\n
.
在 Windows 上,按照惯例,换行符表示为回车符后跟换行符 (CR + LF),即\r\n
.
From the Newline wikipedia page:
Text editors are often used for converting a text file between different newline formats; most modern editors can read and write files using at least the different ASCII CR/LF conventions. The standard Windows editor Notepad is not one of them(although Wordpad is).
文本编辑器通常用于在不同的换行符格式之间转换文本文件;大多数现代编辑器至少可以使用不同的 ASCII CR/LF 约定来读写文件。标准的 Windows 编辑器记事本不是其中之一(尽管写字板是)。
Notepad should display the output correctly if you change the string to:
如果将字符串更改为以下内容,记事本应正确显示输出:
text = "sometext\r\nsomemoretext\r\nlastword";
If you want a platform-independent way of representing a new-line, use System.getProperty("line.separator");
For the specific case of a BufferedWriter
, go with what bemace suggests.
如果您想要一种独立于平台的表示换行符的方式,请使用System.getProperty("line.separator");
对于 a 的特定情况,使用BufferedWriter
bemace 建议的方法。
回答by Brad Mace
This is why you should use BufferedWriter.newLine()
instead of hardcoding your line separators. It will take care of picking the correct version for whatever platform you're currently working on.
这就是为什么你应该使用BufferedWriter.newLine()
而不是硬编码你的行分隔符。它将负责为您当前使用的任何平台选择正确的版本。