3

我可以使用 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());

    }
}

控制台输出:

约翰

跳跃

栅栏

输出.txt

约翰跳过栅栏

4

2 回答 2

5

由于您在 Windows 上,而不是\n使用\r\n(回车 + 换行)。

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

于 2012-09-23T23:04:29.187 回答
-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 语句将其括起来。

于 2012-09-23T23:04:26.243 回答