我使用以下函数将字符串写入文件.字符串使用换行符进行格式化.
例如, text = "sometext\nsomemoretext\nlastword";
我这样做时能够看到输出文件的换行符:
type outputfile.txt
Run Code Online (Sandbox Code Playgroud)
但是,当我在记事本中打开文本时,我看不到换行符.一切都显示在一条线上.
为什么会这样呢?如何确保正确编写文本以便能够在记事本中正确查看(格式化).
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Ani*_*Ani 12
在窗口上,按照惯例,新行表示为回车符,后跟换行符(CR + LF),即\r\n.
文本编辑器通常用于在不同的换行格式之间转换文本文件; 大多数现代编辑器至少可以使用不同的ASCII CR/LF约定来读写文件.标准的Windows编辑器记事本不是其中之一 (尽管是Wordpad).
如果将字符串更改为:记事本应正确显示输出:
text = "sometext\r\nsomemoretext\r\nlastword";
Run Code Online (Sandbox Code Playgroud)
如果您想要一种独立于平台的方式来表示换行,请使用System.getProperty("line.separator");对于a的特定情况BufferedWriter,请使用bemace建议的内容.