Writing a file using BufferedWriter in Java
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 statistics file. Everything in my program works, except for the file write, which I can't figure out why my method isn't working.
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
source to share
3 answers
You should always close opend resources either explicitly or implicitly with Java 7 try-with-resources
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
...
}
In addition, there is a more convenient class for writing text - java.io.PrintWriter
try (PrintWriter pw = new PrintWriter(file)) {
pw.println("Number of words: " + word);
...
}
+3
source to share