Reputation: 11
I am trying to create a GUI where the user fills in TextFields and then the program creates a txt file and writes to it accordingly.
Currently, the program creates the file with specified name, but without writing anything to it(the txt file is blank.) What am I doing wrong?
Code:
try {
File myObj = new File(mNameTF.getText()+".txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
FileWriter myWriter = new FileWriter(mNameTF.getText()+".txt");
BufferedWriter bw = new BufferedWriter(myWriter);
bw.write("Movie: " +mNameTF.getText());
bw.newLine();
bw.write("Actors: "+actorsTF.getText());
bw.newLine();
bw.write("Director: "+ dirTF.getText());
bw.newLine();
bw.write("Producer: "+ prodTF.getText());
bw.newLine();
bw.write("Info: "+descriptionTA.getText());
primaryStage.setScene(sceneA);
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
Upvotes: 1
Views: 164
Reputation: 12346
You should use "try with resources".
try{
File myObj = new File(mNameTF.getText()+".txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
try( FileWriter myWriter = new FileWriter(mNameTF.getText()+".txt");
BufferedWriter bw = new BufferedWriter(myWriter) ){
bw.write("Movie: " +mNameTF.getText());
bw.newLine();
bw.write("Actors: "+actorsTF.getText());
bw.newLine();
bw.write("Director: "+ dirTF.getText());
bw.newLine();
bw.write("Producer: "+ prodTF.getText());
bw.newLine();
bw.write("Info: "+descriptionTA.getText());
primaryStage.setScene(sceneA);
}
} else {
System.out.println("File already exists.");
}
} catch (IOException e){
System.out.println("An error occurred.");
e.printStackTrace();
}
That way the the buffered writer will automatically be closed at the end of the inner try block.
A newer way to handle this would be to use the Files
class.
try(
BufferedWriter bw = Files.newBufferedWriter(
Paths.get(mNameTF.getText()+".txt"),
StandardOpenOption.CREATE_NEW
)
){
//just the write code.
} catch(FileAlreadyExistsException exists){
//this is where you'll handle already exists exception.
} catch(IOException ioe){
//handle ioexception here.
//if you don't want to handle it (which you aren't).
throw new RuntimeException(ioe);
}
Upvotes: 1
Reputation:
BufferedWriter writes text in big 'batches' to reduce the amount of os calls. This means that the text will not appear immediately in the file. If you want to force it to write the text it stores for future writing, you have to call its flush()
method.
You also didn't close the writer, which 1. keeps the file open and uneditable 2. uses unnecessary memory. You can close the writer by calling close()
, which also flushes it.
Upvotes: 0