I have the following code
FileChooser choose = new FileChooser();
choose.getExtensionFilters().add(new FileChooser.ExtensionFilter("Text doc(*.txt)", "*.txt"));
File f = choose.showSaveDialog(stage);
But after clicking on the Save button in the chooser dialog, created file is in File format, but not in .txt, how to fix this?
I got the same problem using JavaFX 2.2. I'm using following workaround:
FileChooser choose = new FileChooser();
choose.getExtensionFilters().add(new FileChooser.ExtensionFilter("Text doc(*.txt)", "*.txt"));
File f = choose.showSaveDialog(stage);
if(!f.getName().contains(".")) {
f = new File(f.getAbsolutePath() + ".txt");
}
For me it worked best, to
FileChooser choose = new FileChooser();
choose.getExtensionFilters().add(new FileChooser.ExtensionFilter("Text doc(*.txt)", "*.txt"));
choose.setInitialFileName("*.txt");
File file = choose.showSaveDialog(stage);
if (file != null) {
if (file.getName().endsWith(".txt")) {
// do the operation with the file (i used a builder)
} else {
throw new Exception(file.getName() + " has no valid file-extension.");
}
}
The problem of replacing the extension manually like that:
if(!f.getName().contains(".")) {
f = new File(f.getAbsolutePath() + ".txt");
}
is, that a file without an extension might not exist, but if the file existed with the extension, it was overwritten without any warning. not expected behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With