【问题标题】:printing to text file line by line with toString使用 toString 逐行打印到文本文件
【发布时间】:2012-09-15 10:30:16
【问题描述】:

我可以使用 toString 逐行打印到控制台,但是当我将它放入文本文件时它为什么不一样呢?

public class NewClass
{

    @Override
    public String toString()
    {
        return ("John " + "\n" + "jumps " + "\n" + "fences");
    }
}


import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;


public class Sandbox
{
    public static void main(String[] args) throws IOException
    {
        NewClass object = new NewClass();            

        FileWriter file = new FileWriter("output.txt");
        PrintWriter output = new PrintWriter(file);
        output.println(object.toString());    
        output.close(); 
        System.out.println(object.toString());

    }
}

控制台输出:

约翰

跳跃

栅栏

output.txt

约翰跳过栅栏

【问题讨论】:

  • 您使用的是什么操作系统以及哪个文本编辑器?
  • @user1615805 记事本需要 CRLF (\r\n)

标签: java file io newline


【解决方案1】:

Windows 文件需要 \r\n(回车和换行)。 Unix 文件只需要 \n。要使其与两者兼容,您可以使用 FileOutputStream:

try {
    FileOutputStream file = new FileOutputStream(new File("output.txt"));
    byte[] b = object.toString().getBytes();
    file.write(b);
} catch (Exception e) {
    //take care of IO Exception or do nothing here
}

您可能需要用 try-catch 语句将其括起来,如图所示。

【讨论】:

    【解决方案2】:

    由于您使用的是 Windows,因此请使用 \r\n(回车 + 换行)代替 \n

    或者更好的是,使用System.getProperty("line.separator")获取操作系统用来分隔文本文件中的行的序列

    【讨论】:

    • 嗯...PrintWriter 的规范:这些方法使用平台自己的行分隔符概念,而不是换行符。
    • @oldrinb:是的,但是 OP 正在使用 PrintWriter 打印 single 行。其他的硬编码在NewClass#toString(),使用\n
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 2022-07-06
    相关资源
    最近更新 更多