Set the initial file extension when saving the file

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 the "Save" button in the selection dialog box, the created file is in the "File" format, but not in .txt, how to fix this?

+5
source share
2 answers

I have the same problem using JavaFX 2.2. I am using the 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");
}
+10
source

It worked best for me

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.");
  }
}

Manual replacement problem manually:

if(!f.getName().contains(".")) {
  f = new File(f.getAbsolutePath() + ".txt");
}

It means that the file without the extension may not exist, but if the file exists with the extension, it was overwritten without warning. not expected behavior.

+7
source

All Articles