Benjamin Benjamin - 3 months ago 7
Java Question

FileWriter and BufferedWriter not writing to file

I am having issues with the FileWriter and BufferedWriter classes. After declaring, initializing, and calling their write methods the files created have no contents. I have run debug mode and seen that the toString function is working perfectly and is returning a valid String. What am I missing?

public String toString(){
String accountInfo = "";

//creates a String of the account info according to an easily parsed
//format
for (int counter = 0; counter < accounts.size(); counter++){
if (counter == 0){
accountInfo = accounts.get(counter).getInfo();
} else{
accountInfo += "\n" + accounts.get(counter).getInfo();
}
}
return accountInfo;
}

public void saveToFile(){
File customer = new File( name + ".txt");
try {
FileWriter custWriter = new FileWriter(customer);
BufferedWriter custBuffer = new BufferedWriter(custWriter);
custBuffer.write(this.toString());

//commented out when I thought I needed to use a BufferedWriter
//custWriter.write(this.toString());
} catch (IOException e) {
e.printStackTrace();
}
}

Answer

You have to call the close method on your writers!

One way to get that automatically is to use try-with-resources:

try (BufferedWriter custBuffer = new BufferedWriter(new FileWriter ...)) {
  custBuffer.write(this.toString());
}

This will automatically close the writer; if you go with your current code; try adding writer.close() in the end.

Comments