Java FileFilter是abstract class,所以必須自己實做methods,詳細API可參考Class FileFilter
可以提供JFileChooser物件來過濾指定的檔案類型,實作可參考How to Use File Choosers
範例程式如下:
/* MyFileFilter.java */
import java.io.File;
import javax.swing.filechooser.FileFilter;
public class MyFileFilter extends FileFilter {
String extension;
String description;
public MyFileFilter(String ext, String desc){
this.extension = ext;
this.description = desc;
}
public static String getExtension(File f) {
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i+1).toLowerCase();
}
return ext;
}
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String ext = this.getExtension(f);
if (ext != null) {
if (ext.equals(this.extension)) {
return true;
} else {
return false;
}
}
return false;
}
public String getDescription() {
return this.description;
}
}
在FileFilter的物件,可用setFileFilter method來呼叫,如下所示:
JFileChooser fc = new JFileChooser( CurrentDirectory );
fc.setFileFilter(new MyFileFilter("ext", "file description")); //ext可為任意的副檔名
也可以用addChoosableFileFilter method:
fc.addChoosableFileFilter(new MyFileFilter("ext1", "description1") );
fc.addChoosableFileFilter(new MyFileFilter("ext2", "description2") );
可以提供JFileChooser物件來過濾指定的檔案類型,實作可參考How to Use File Choosers
範例程式如下:
/* MyFileFilter.java */
import java.io.File;
import javax.swing.filechooser.FileFilter;
public class MyFileFilter extends FileFilter {
String extension;
String description;
public MyFileFilter(String ext, String desc){
this.extension = ext;
this.description = desc;
}
public static String getExtension(File f) {
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i+1).toLowerCase();
}
return ext;
}
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String ext = this.getExtension(f);
if (ext != null) {
if (ext.equals(this.extension)) {
return true;
} else {
return false;
}
}
return false;
}
public String getDescription() {
return this.description;
}
}
在FileFilter的物件,可用setFileFilter method來呼叫,如下所示:
JFileChooser fc = new JFileChooser( CurrentDirectory );
fc.setFileFilter(new MyFileFilter("ext", "file description")); //ext可為任意的副檔名
也可以用addChoosableFileFilter method:
fc.addChoosableFileFilter(new MyFileFilter("ext1", "description1") );
fc.addChoosableFileFilter(new MyFileFilter("ext2", "description2") );
全站熱搜
留言列表