Java:BufferedWriter跳过换行符

我使用以下函数将字符串写入文件。 字符串使用换行符进行格式化。

例如, text = "sometext\nsomemoretext\nlastword";

我这样做时能够看到输出文件的换行符:

 type outputfile.txt 

但是,当我在记事本中打开文本时,我看不到换行符。 一切都显示在一条线上。

为什么会这样呢? 如何确保正确编写文本以便能够在记事本中正确查看(格式化)。

  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(); } } } 

在Windows上,按照惯例,新行表示为回车符,后跟换行符(CR + LF),即\r\n

从Newline维基百科页面 :

文本编辑器通常用于在不同的换行格式之间转换文本文件; 大多数现代编辑器至少可以使用不同的ASCII CR / LF约定来读写文件。 标准的Windows编辑器记事本不是其中之一 (尽管是Wordpad)。

如果将字符串更改为:记事本应正确显示输出:

 text = "sometext\r\nsomemoretext\r\nlastword"; 

如果您想要一种独立于平台的方式来表示换行,请使用System.getProperty("line.separator"); 对于BufferedWriter的具体情况,请参考bemace建议的内容。

这就是为什么你应该使用BufferedWriter.newLine()而不是硬编码你的行分隔符。 它将负责为您当前正在处理的任何平台选择正确的版本。