【问题标题】:Strings are not written to a new line字符串不写入新行
【发布时间】:2012-06-16 04:50:49
【问题描述】:

以下 sn-p 尝试将某个目录中存在的目录和文件的名称写入文本文件。每个名称应写入单独的行。相反,它将每个名称打印在同一行上。为什么会这样?

        try {
        File listFile = new File("E:" + System.getProperty("file.separator") + "Shiv Kumar Sharma Torrent"+ System.getProperty("file.separator") +"list.txt");
        FileWriter writer = new FileWriter(listFile,true);
        Iterator iterator = directoryList.iterator();
        while(iterator.hasNext()) {
            writer.write((String)iterator.next());
            writer.write("\n"); // Did this so each name is on a new line
        }
        writer.close();
    }catch(Exception exc) {
        exc.printStackTrace();
    }

输出:

我在哪里做错了?

【问题讨论】:

    标签: java file-io newline


    【解决方案1】:

    当您需要文本格式时,请始终使用PrintWriter。
    正确的做法是将 writer 包装在 PrintWriter 中并使用 println() 方法,例如:

    PrintWriter printWriter = new PrintWriter(writer);
    printWriter.println();
    

    【讨论】:

    • 其实newLine()是BufferedWriter类的一个方法。
    • +1 建议使用PrintWriter 而不是FileWriter:)
    【解决方案2】:

    如果您使用的是 Windows,请使用 \r\n 而不是 \n。

    或者对于独立于操作系统,使用:

    System.getProperty("line.separator");
    

    【讨论】:

      【解决方案3】:

      如果您在 Windows 平台上,则应将下一行写为“\r\n”。

      Windows 的下一行是“\r\n”

      Mac 的下一行是“\n”

      或者,使用 System.getProperty("line.separator") 作为换行符。它会自动为其运行的系统确定正确的换行符。这应该是最佳实践,因为 Java 预计会在不同的操作系统上执行相同的操作。

      【讨论】:

        【解决方案4】:

        如果你要使用 BufferedWriter :

         File f = new File("C:/file.txt");
         BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
         bw.write("Hello");
         bw.newLine();   // new line
         bw.write("How are you?");
         bw.close();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-04-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-24
          • 2021-09-17
          相关资源
          最近更新 更多