JFileChooser,保存多种文件类型
JFileChooser, save multiple file types
我打开多个文件类型没有问题,但我希望该选项能够保存多个文件类型。我不知道如何获取用户选择的将其文件类型另存为的选项。
这是我的代码:
//.txt and .encm files are allowed
final JFileChooser txtOrEncmChooser = new JFileChooser(new File(System.getProperty("user.dir")));
//only allow user to use .txt and .encm files
txtOrEncmChooser.addChoosableFileFilter(new FileNameExtensionFilter("Encrypted Data File (*.encm)", "encm"));
txtOrEncmChooser.addChoosableFileFilter(new FileNameExtensionFilter("Text File (*.txt)", "txt"));
txtOrEncmChooser.setAcceptAllFileFilterUsed(false);
//displays save file dialog
int returnVal = txtOrEncmChooser.showSaveDialog(FileEncryptionFilter.this);
//use chose to save file
if (returnVal == JFileChooser.APPROVE_OPTION)
{
//selects file
File fileName = txtOrEncmChooser.getSelectedFile();
/****The problem is here, how do I figure out what file type the user selected?****/
if .txt is selected{
String filePath = fileName.getPath() + ".txt"; //file path
}
else if .encm is selected
{
String filePath = fileName.getPath() + ".encm"; //file path
}
}
我在论坛上搜索了解决方案,但我只找到了打开多个文件类型的解决方案,而不是保存多个文件类型的解决方案。
https://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html#getFileFilter()
FileNameExtensionFilter f = (FileNameExtensionFilter) txtOrEncmChooser.getFileFilter();
因为 getExtensions()
returns 一个数组,你将不得不遍历所有的扩展。如果你确定它只包含一个元素,当然你就不需要这样做了。例如,只需检查 f.getExtensions()[0].equals("txt")
。您还可以将文件过滤器创建为局部变量,然后将它们与选定的过滤器进行比较。
我打开多个文件类型没有问题,但我希望该选项能够保存多个文件类型。我不知道如何获取用户选择的将其文件类型另存为的选项。
这是我的代码:
//.txt and .encm files are allowed
final JFileChooser txtOrEncmChooser = new JFileChooser(new File(System.getProperty("user.dir")));
//only allow user to use .txt and .encm files
txtOrEncmChooser.addChoosableFileFilter(new FileNameExtensionFilter("Encrypted Data File (*.encm)", "encm"));
txtOrEncmChooser.addChoosableFileFilter(new FileNameExtensionFilter("Text File (*.txt)", "txt"));
txtOrEncmChooser.setAcceptAllFileFilterUsed(false);
//displays save file dialog
int returnVal = txtOrEncmChooser.showSaveDialog(FileEncryptionFilter.this);
//use chose to save file
if (returnVal == JFileChooser.APPROVE_OPTION)
{
//selects file
File fileName = txtOrEncmChooser.getSelectedFile();
/****The problem is here, how do I figure out what file type the user selected?****/
if .txt is selected{
String filePath = fileName.getPath() + ".txt"; //file path
}
else if .encm is selected
{
String filePath = fileName.getPath() + ".encm"; //file path
}
}
我在论坛上搜索了解决方案,但我只找到了打开多个文件类型的解决方案,而不是保存多个文件类型的解决方案。
https://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html#getFileFilter()
FileNameExtensionFilter f = (FileNameExtensionFilter) txtOrEncmChooser.getFileFilter();
因为 getExtensions()
returns 一个数组,你将不得不遍历所有的扩展。如果你确定它只包含一个元素,当然你就不需要这样做了。例如,只需检查 f.getExtensions()[0].equals("txt")
。您还可以将文件过滤器创建为局部变量,然后将它们与选定的过滤器进行比较。