Write file using BufferedWriter in Java [duplicate

2019-01-26 15:38发布

This question already has an answer here:

I am doing a lab where we have to read in an external file, take some statistics on the data, and then create and write a new file with the stats. Everything in my program works except for writing the file, which I cannot understand why my method won't work.

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

3条回答
Animai°情兽
2楼-- · 2019-01-26 16:13

You have to close your BufferedWriter using close():

writer.close();
查看更多
仙女界的扛把子
3楼-- · 2019-01-26 16:15

You should always close opend resources explicitly or implicitly with Java 7 try-with-resources

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

besides, there is a more convenient class to write text - java.io.PrintWriter

try (PrintWriter pw = new PrintWriter(file)) {
    pw.println("Number of words: " + word);
    ...
}
查看更多
贪生不怕死
4楼-- · 2019-01-26 16:22

You have to flush and close your writer:

writer.flush();
writer.close();
查看更多
登录 后发表回答