Set initial file extension while saving the file


Question

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?

1
5
5/9/2012 9:37:21 PM

Accepted Answer

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");
}
14
11/2/2012 2:35:24 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon