我正在制作一个桌面应用程序,它有一个JFileChooser(ShowSaveDialog)函数.. 当我试图保存示例文本文件时,程序没有得到我选择的扩展文件。我正在尝试使用if else或switch语句,我无法弄清楚我将使用什么命令来获取字符串/ Int如果选择pdf,word或txt扩展名为条件的值...
public class Save {
static boolean flag = false;
public static void main(String[] args) throws IOException, SQLException {
JFileChooser saveFile = new JFileChooser();
saveFile.setDialogTitle("Save as");
FileNameExtensionFilter File_ext_txt =
new FileNameExtensionFilter("Text Documents(*.txt)", "txt");
FileNameExtensionFilter File_ext_pdf =
new FileNameExtensionFilter("PDF", "pdf");
FileNameExtensionFilter File_ext_doc =
new FileNameExtensionFilter("Word 97-2003 Document", "doc");
saveFile.addChoosableFileFilter(File_ext_pdf);
saveFile.addChoosableFileFilter(File_ext_doc);
saveFile.addChoosableFileFilter(File_ext_txt);
FileFilter extension = saveFile.getFileFilter();
int userSelection = saveFile.showSaveDialog(null);
File File_Path = saveFile.getSelectedFile();
String fullPath = File_Path.getAbsolutePath();
String Ext = null;
if (userSelection == JFileChooser.APPROVE_OPTION){
if(extension == File_ext_txt){
Ext = "txt";
}
File save = new File(fullPath+"."+Ext);
System.out.println(extension);
flag = save.createNewFile();
}
}
}
答案 0 :(得分:8)
之前我遇到过这个问题。这是我可以使用的一个程序中的实用程序函数,而不是JFileChooser.getSelectedFile
,以获取扩展名。
/**
* Returns the selected file from a JFileChooser, including the extension from
* the file filter.
*/
public static File getSelectedFileWithExtension(JFileChooser c) {
File file = c.getSelectedFile();
if (c.getFileFilter() instanceof FileNameExtensionFilter) {
String[] exts = ((FileNameExtensionFilter)c.getFileFilter()).getExtensions();
String nameLower = file.getName().toLowerCase();
for (String ext : exts) { // check if it already has a valid extension
if (nameLower.endsWith('.' + ext.toLowerCase())) {
return file; // if yes, return as-is
}
}
// if not, append the first extension from the selected filter
file = new File(file.toString() + '.' + exts[0]);
}
return file;
}