我正在做一個實驗,我們必須在外部文件中讀取數據,對數據進行一些統計,然後創建並寫入一個包含統計數據的新文件。除了編寫文件外,我的程序中的所有內容都工作正常,我無法理解爲什麼我的方法無法工作。使用Java中的BufferedWriter編寫文件
BufferedWriter writer;
public void writeStats(int word, int numSent, int shortest, int longest, int average)
{
try
{
File file = new File("jefferson_stats.txt");
file.createNewFile();
writer = new BufferedWriter(new FileWriter(file));
writer.write("Number of words: " + word);
writer.newLine();
writer.write("Number of sentences: " + numSent);
writer.newLine();
writer.write("Shortest sentence: " + shortest + " words");
writer.newLine();
writer.write("Longest sentence: " + longest + " words");
writer.newLine();
writer.write("Average sentence: " + average + " words");
}
catch(FileNotFoundException e)
{
System.out.println("File Not Found");
System.exit(1);
}
catch(IOException e)
{
System.out.println("something messed up");
System.exit(1);
}
}
你可能希望你的最後writer.write後writer.newLine()()。 –