2016-11-22 27 views
0

例如可以說我有以下字符串,如何保存文件,正是因爲它是從一個字符串的Java

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

你在Windows上,不是'cha? – nasukkin

回答

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(); 
    } 
相關問題