5

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 );
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Paidenwaffle
  • 163
  • 1
  • 1
  • 11

3 Answers3

18

You have to flush and close your writer:

writer.flush();
writer.close();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
BackSlash
  • 21,927
  • 22
  • 96
  • 136
  • 6
    close() would implicitly call flush , you dont need to call flush explicitly – PermGenError Jan 24 '13 at 14:27
  • 1
    from Oracle's documentation: `Flush: Flushes this output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.` On buffered streams it is recommendend to use `flush()` and then `close()` – BackSlash Jan 24 '13 at 14:29
3

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);
    ...
}
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

You have to close your BufferedWriter using close():

writer.close();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
PermGenError
  • 45,977
  • 8
  • 87
  • 106