例如,假设我有以下字符串,
String str = "Patient: " + patient +
"\nMonth: " + month +
"\nDay : " + day +
"\nYear: " + year
+"\nDescription: " + description;
//And I write this data to a file,
PrintWriter outputFile = new PrintWriter("hello.txt");
outputFile.println(str);
然后当我打开它时,文件上的结果只是一行, 有没有办法,只需将格式作为传递给文件的字符串。?
提前谢谢。
答案 0 :(得分:2)
\ n在UNIX上按预期工作。使用Windows可能需要\ r \ n。请查看https://softwareengineering.stackexchange.com/questions/29075/difference-between-n-and-r-n
答案 1 :(得分:1)
就像在Linux系统上编写的一样,它对我有用。如果您使用的是Windows机器,请尝试使用“\ r \ n”作为新行而不是“\ n”。另外一个好习惯是在打开PrintWriter时指定编码。理想情况下,您可以使用System.getProperty(“line.separator”)来获取与平台相关的行分隔符。
String lineSeparator = System.getProperty("line.separator");
String str = "Patient: " + "a" +
lineSeparator + "Month: " + "a" +
lineSeparator + "Day : " + "a" +
lineSeparator + "Year: " + "a"
lineSeparator + "Description: " + "a";
try {
PrintWriter outputFile = new PrintWriter("hello.txt", "UTF-8");
outputFile.println(str);
outputFile.close();
System.out.println("writing file");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}