【问题标题】:Not the correct input不是正确的输入
【发布时间】:2026-01-03 14:00:01
【问题描述】:

我想将一些数据写入文件,这是我的代码:

for (Season s : seasons) {
            if (s.getYear() >= start && s.getYear() <= end) {
                line += s.getYear() + ", " + s.getWinTeamName() + ", "
                        + s.getMinorPremiersTeam() + ", "
                        + s.getWoodenSpoonTeam()+ "\n"; }
}
System.out.println("File created.\n"); // Informing the user about
// the creation of the file.
out.write(line);
out.close();

我的文件已创建,但这是我得到的:

2005, Wests Tigers, Parramatta, Newcastle2006, Broncos, Storm, Rabbitohs

但我希望它是:

2005, Wests Tigers, Parramatta, Newcastle
2006, Broncos, Storm, Rabbitohs

我认为在行变量末尾添加“\n”可以解决这个问题,但它没有。

关于如何解决这个问题的任何建议?

【问题讨论】:

  • 好像没问题。尝试将 \n 替换为 \r\n,某些文本编辑器(例如记事本)无法正确显示 \n。
  • 您的 println() 不需要\n。方法名代表print line,所以它已经使用了新行。
  • 对于更通用的代码,您可能需要使用a line separator function

标签: java arrays file-io io


【解决方案1】:

您需要使用系统特定的换行符分隔符。见System.lineSeparator

【讨论】:

    【解决方案2】:

    如果您使用java.io.BufferedWriter.newLine() 方法将插入适当的行分隔符。

    for (Season s : seasons) 
    {
       if (s.getYear() >= start && s.getYear() <= end)
       {
          String line = s.getYear() + ", " + s.getWinTeamName() + ", "
                            + s.getMinorPremiersTeam() + ", "
                            + s.getWoodenSpoonTeam();
          out.write(line);
          out.newLine();
       }
    }
    

    【讨论】:

      【解决方案3】:
      for (Season s : seasons) {
              if (s.getYear() >= start && s.getYear() <= end) {
                  line += s.getYear() + ", " + s.getWinTeamName() + ", "
                          + s.getMinorPremiersTeam() + ", "
                          + s.getWoodenSpoonTeam()+ "\r\n"; }
      }
      
      System.out.println("File created.\n"); // Informing the user about
                                            // the creation of the file.
      out.write(line);
      out.close();
      

      【讨论】:

        最近更新 更多