2013-05-31 121 views
1

我想寫一些數據到一個文件,這裏是我的代碼:不正確的輸入

for (Season s : seasons) { 
      if (s.getYear() >= start && s.getYear() <= end) { 
       line += s.getYear() + ", " + s.getWinTeamName() + ", " 
         + s.getMinorPremiersTeam() + ", " 
         + s.getWoodenSpoonTeam()+ "\n"; } 
} 
System.out.println("File created.\n"); // Informing the user about 
// the creation of the file. 
out.write(line); 
out.close(); 

創建我的文件,但是這是我得到:

2005, Wests Tigers, Parramatta, Newcastle2006, Broncos, Storm, Rabbitohs 

但我想它是:

2005, Wests Tigers, Parramatta, Newcastle 
2006, Broncos, Storm, Rabbitohs 

我認爲在行變量的末尾添加「\ n」會修復,但它沒有。 關於我如何解決這個問題的任何建議?

+0

這似乎確定。嘗試用\ r \ n替換\ n,某些文本編輯器(例如記事本)不會正確顯示\ n。 – manabreak

+0

您的println()不需要'\ n'。 methodname代表'print line',因此它已經使用了新行。 – Aquillo

+0

對於更通用的代碼,您可能需要使用[行分隔符函數](http://stackoverflow.com/questions/207947/java-how-do-i-get-a-platform-independent-new-line-字符)代替。 – Dukeling

回答

1

如果使用java.io.BufferedWriter,則.newLine()方法將插入相應的行分隔符。

for (Season s : seasons) 
{ 
    if (s.getYear() >= start && s.getYear() <= end) 
    { 
     String line = s.getYear() + ", " + s.getWinTeamName() + ", " 
         + s.getMinorPremiersTeam() + ", " 
         + s.getWoodenSpoonTeam(); 
     out.write(line); 
     out.newLine(); 
    } 
} 
0
for (Season s : seasons) { 
     if (s.getYear() >= start && s.getYear() <= end) { 
      line += s.getYear() + ", " + s.getWinTeamName() + ", " 
        + s.getMinorPremiersTeam() + ", " 
        + s.getWoodenSpoonTeam()+ "\r\n"; } 
} 

System.out.println("File created.\n"); // Informing the user about 
             // the creation of the file. 
out.write(line); 
out.close(); 
+0

感謝來自@manabreak的建議 – roro