我可以使用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());
}
}
CONSOLE OUTPUT:
约翰
跳跃
围栏
output.txt的
约翰跳过围栏
答案 0 :(得分:5)
由于您使用的是Windows,而不是\n
使用\r\n
(回车+换行符)。
或者更好的是,使用System.getProperty("line.separator")
获取操作系统用来分隔文本文件中的行的序列。
答案 1 :(得分:-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语句将其包围,如图所示。