我有以下代码
FileChooser choose = new FileChooser();
choose.getExtensionFilters().add(new FileChooser.ExtensionFilter("Text doc(*.txt)", "*.txt"));
File f = choose.showSaveDialog(stage);Run Code Online (Sandbox Code Playgroud)
但是在单击选择器对话框中的"保存"按钮后,创建的文件是文件格式,但不是.txt,如何解决这个问题?
Tar*_*aro 14
我使用JavaFX 2.2遇到了同样的问题.我正在使用以下解决方法:
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");
}
Run Code Online (Sandbox Code Playgroud)
小智 8
对我来说,它最有效
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.");
}
}
Run Code Online (Sandbox Code Playgroud)
手动替换扩展的问题如下:
if(!f.getName().contains(".")) {
f = new File(f.getAbsolutePath() + ".txt");
}
Run Code Online (Sandbox Code Playgroud)
是,没有扩展名的文件可能不存在,但如果文件存在扩展名,则会被覆盖而没有任何警告.不期望的行为.