java 保存对话框不会向文件添加扩展名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16440987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save dialog doesn't add extension to file
提问by Dan
I have a button that opens a save dialog window with default extension filters set. When I save a file it creates it in the correct folder, but it doesn't add the extension on the end. How would I go about adding the extension to the end of the file based on the filter? Here is my save file button code:
我有一个按钮可以打开一个带有默认扩展过滤器设置的保存对话框窗口。当我保存文件时,它会在正确的文件夹中创建它,但它不会在末尾添加扩展名。我将如何根据过滤器将扩展名添加到文件末尾?这是我的保存文件按钮代码:
btnNewButton = new JButton("Export File");
btnNewButton.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
final JFileChooser finder = new JFileChooser();
finder.setFileFilter(new FileNameExtensionFilter("Board Files", "boa"));
int returnVal = finder.showSaveDialog(null);
if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
java.io.File file = finder.getSelectedFile();
String file_name = file.toString();
JOptionPane.showMessageDialog(null, file_name);
WriteFile data = new WriteFile(file_name);
try {
data.writeToFile("Testing 1");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
});
回答by PurkkaKoodari
You could add the extension yourself if it is not done already by the user.
如果用户尚未添加扩展,您可以自己添加。
String file_name = file.toString();
if (!file_name.endsWith(".boa"))
file_name += ".boa";
回答by mschenk74
The filter is just for filtering the existing files inside the selected folder. Since there is the possibility to have more than one extension inside the filter, only you can decide which extension to add.
过滤器仅用于过滤所选文件夹中的现有文件。由于过滤器内可能有多个扩展名,因此只有您可以决定添加哪个扩展名。
The adding itself could be done like in the answer above.
添加本身可以像上面的答案一样完成。