现在的位置: 首页 > 综合 > 正文

JAVA文件选择JFileChooser使用例子

2013年10月02日 ⁄ 综合 ⁄ 共 1254字 ⁄ 字号 评论关闭

JFileChooser类的使用非常简单,主要是对一些属性的设置,以及文件筛选器的使用。

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()
		}
	}
}

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();
		}
	}
}

抱歉!评论已关闭.