我可以使用 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
约翰跳过栅栏
最佳答案
因为你在 Windows 上,而不是 \n
使用 \r\n
(回车 + 换行)。
或者更好的是,使用 System.getProperty("line.separator")
获取操作系统用于分隔文本文件中的行的序列。
关于java - 使用 toString 逐行打印到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12556982/