The first time I save a file, even if it exists, I get the result I want. The file is overwritten. Now If I save again the text is appended to the file instead of overwriting. I have tried applying the approaches from similar questions I found answered here but none solve this. This is not answered by the possible duplicate. When I save a file the first time the behavior is what I want, the file is overwritten. However, all subsequent saves with the java window open append. That is incorrect. I suspect the file may not be closing after writing.
Edits: This is a javafx package so the minimal amount of code to run is going to be a bit long but here it goes.
MainController:
public class MainController{
/** Holder of a switchable vista. */
@FXML public StackPane vistaHolder;
@FXML
public void programExit(){System.exit(0);}
public void permutationAnalyzer(){VistaNavigator.loadVista(VistaNavigator.VISTA_3);}
@FXML
public void saveFile() throws IOException {
OptionsDataCollector.generateOptionsFile();
}
public void setVista(Node node) {
vistaHolder.getChildren().setAll(node);
}
}
The data being saved:
public class OptionsDataCollector{
public static void generateOptionsFile() throws IOException {
StringBuilder moduleData = new StringBuilder();
moduleData.append("--target_perm_group_size\t").append(targetGroupSize).append("\n");
moduleData.append("--prog_check\t").append(progCheck).append("\n");
FileSaveUtility.fileSaveWindow(moduleData.toString());
//The next line is the answer.
moduleData.setLength(0);
}
}
FileSave:
public class FileSaveUtility {
private static void saveFile(String content, File file) throws IOException {
FileWriter fileWriter = new FileWriter(file.getAbsoluteFile(), false);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(content);
bufferedWriter.close();
//fileWriter.write(content);
//fileWriter.close();
}
public static void fileSaveWindow(String outFileData) throws IOException {
Stage primaryStage = new Stage();
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(extFilter);
fileChooser.setInitialFileName("run_Volundr.txt");
File file = fileChooser.showSaveDialog(primaryStage);
if(file != null){
saveFile(outFileData, file);
//primaryStage.close();
}
}
}
I have not included the FXML files or the MainApp that generates it. I can add them if anyone wants. I have tried closing the stage, using StandardOpenOptions.Truncate_Exsisting and Files.deleteIfExsists. There is an object or stream not closing somewhere.