如何在文件中打开具有特定扩展名的文件对话
答
如果您可以使用JFileChooser
,则可以使用JFileChooser.addChoosableFileFilter()
按扩展名筛选文件。
JFileChooser fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "*.fct, *.wtg";
}
@Override
public boolean accept(File f) {
return f.getName().endsWith(".fcg") ||
f.getName().endsWith(".wtg");
}
});
答
您可以使用此验证码选择一个文件并读取
public void openFile() throws Exception {
int rowCount = 0;
int rowNo = 2;
String id = "";
String name = "";
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(new JPanel());
if (result == JFileChooser.APPROVE_OPTION) {
String file = String.valueOf(fc.getSelectedFile());
File fil = new File(file);
System.out.println("File Selected" + file);
FileInputStream fin = new FileInputStream(fil);
int ch;
while ((ch = fin.read()) != -1) {
System.out.print((char)ch);
}
} else {
}
}
+0
这并不回答OP的问题。顺便说一句 - 什么是空的'else'声明打算实现? – 2011-05-07 19:46:17
答
由于这是我的谷歌搜索#1,这是为我工作最好的解决办法:
How to restrict file choosers in java to specific files
细节:
JFileChooser open = new JFileChooser(openPath);
FileNameExtensionFilter filter = new FileNameExtensionFilter("PLSQL Files", "sql", "prc", "fnc", "pks"
, "pkb", "trg", "vw", "tps" , "tpb");
open.setFileFilter(filter);
谢谢,我将不得不使用JFileChooser如果我不能使用fileDialog – Dawnlight 2011-05-07 19:03:37