Java:BufferedWriter跳过换行符

dev*_*ull 5 java

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

例如, 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.

Newline维基百科页面:

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

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

text = "sometext\r\nsomemoretext\r\nlastword";
Run Code Online (Sandbox Code Playgroud)

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

  • 哦.现在我正在使用System.getProperty("line.separator"); 不能使用BufferedWriter.newLine(),因为我需要在写入之前填充完整的字符串. (3认同)

Bra*_*ace 9

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