Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set initial file extension while saving the file

Tags:

file

javafx

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?

like image 595
4lex1v Avatar asked May 09 '12 21:05

4lex1v


2 Answers

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");
}
like image 88
Taro Avatar answered Nov 01 '22 11:11

Taro


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.

like image 27
sihu Avatar answered Nov 01 '22 11:11

sihu