【问题标题】:Writing in files without overflow写入文件而不溢出
【发布时间】:2026-01-08 06:55:01
【问题描述】:

我有以下代码:

FileWriter filewriter = null;
try { filewriter = new FileWriter("outUser.txt", true); } 
catch (IOException e1) { e1.printStackTrace(); }

try {
    filewriter.write(s1+"\n");
    filewriter.flush();
}
catch (IOException e1) { e1.printStackTrace(); }

它应该在outUser 文件上写入s1 string 和换行符。它只写s1,不写换行符。我还尝试使用等于\n 的新字符串,并在写入时将其附加到s1,但仍然无效。大家有什么答案吗?

【问题讨论】:

  • 如何验证没有写入换行符?无论您使用什么,都可能期望 \r\n 作为行尾(就像大多数 Windows 工具一样)。
  • 您可以在运行程序时分享输出吗?

标签: java file-io io


【解决方案1】:

应该有换行符,但请记住,不同的操作系统具有不同的换行符。
如果运气不好,可以随时尝试BufferedWriter.newLine()

【讨论】:

    【解决方案2】:

    不同的操作系统有不同的方式来表示换行符。

    例如,\n 用于 UNIX,而\r\n 用于 Windows。

    This 回答为什么 windows 使用\r

    您可以使用System.lineSeparator(),它返回与系统相关的行分隔符字符串。

    【讨论】:

      【解决方案3】:

      使用记事本++ 等文本编辑器打开您的outUser.txt 并启用“不可打印”字符。您应该会看到一个CR/LF,即\n

      【讨论】:

        【解决方案4】:

        以下应该可以工作

        FileWriter filewriter = null;
        try {
                             filewriter = new FileWriter("outUser.txt", true);
                             BufferedWriter buffWriter = new BufferedWriter(fileWriter);  
                          } catch (IOException e1) {
                             e1.printStackTrace();
                          }
                          try {
                              buffwriter.write(s1+"\n");
                              buffWriter.newLine();
                             buffwriter.flush();
                             }
                          catch (IOException e1) {
                             e1.printStackTrace();
                          }
        

        【讨论】:

          【解决方案5】:

          这样做

          FileWriter filewriter = null;
          
                   try {
                       filewriter = new FileWriter("c:\\outUser.txt", true);
                    } catch (IOException e1) {
                       e1.printStackTrace();
                    }
                    try {
                        filewriter.write("hi"+System.getProperty("line.separator"));
                        filewriter.write("asd");
                       filewriter.flush();
                       }
                    catch (IOException e1) {
                       e1.printStackTrace();
                    }
          

          使用行分隔符属性将下一行打印到文件。

          【讨论】: