5

我正在做一个实验室,我们必须读入一个外部文件,对数据进行一些统计,然后使用统计数据创建和写入一个新文件。除了编写文件外,我的程序中的所有内容都可以正常工作,我无法理解为什么我的方法不起作用。

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 );
    }
}
4

3 回答 3

18

你必须刷新并关闭你的作家:

writer.flush();
writer.close();
于 2013-01-24T14:26:40.593 回答
3

您应该始终使用 Java 7 try-with-resources 显式或隐式关闭打开的资源

    try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
         ...            
    }

此外,还有一个更方便的类来编写文本 - java.io.PrintWriter

try (PrintWriter pw = new PrintWriter(file)) {
    pw.println("Number of words: " + word);
    ...
}
于 2013-01-24T14:45:30.240 回答
0

您必须使用close()关闭BufferedWriter

writer.close();
于 2013-01-24T14:25:25.123 回答