JAVA文件选择JFileChooser使用例子 http://blog.csdn.net/pandakong/article/details/7088301
JFileChooser类的使用非常简单,主要是对一些属性的设置,以及文件筛选器的使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import javax.swing.JFileChooser; public class FileChooser { public static void main(String[] args) { JFileChooser fc = new JFileChooser("D:"); //是否可多选 fc.setMultiSelectionEnabled(false); //选择模式,可选择文件和文件夹 fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); // fc.setFileSelectionMode(JFileChooser.FILES_ONLY); // fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); //设置是否显示隐藏文件 fc.setFileHidingEnabled(true); fc.setAcceptAllFileFilterUsed(false); //设置文件筛选器 fc.setFileFilter(new MyFilter("java")); fc.setFileFilter(new MyFilter("zip")); int returnValue = fc.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { //fc.getSelectedFile() //fc.getSelectedFiles() } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import java.io.File; import javax.swing.filechooser.FileFilter; public class MyFilter extends FileFilter { private String ext; public MyFilter(String extString) { this.ext = extString; } public boolean accept(File f) { if (f.isDirectory()) { return true; } String extension = getExtension(f); if (extension.toLowerCase().equals(this.ext.toLowerCase())) { return true; } return false; } public String getDescription() { return this.ext.toUpperCase(); } private String getExtension(File f) { String name = f.getName(); int index = name.lastIndexOf('.'); if (index == -1) { return ""; } else { return name.substring(index + 1).toLowerCase(); } } } |