如何对.txt文件进行过滤?
我写了这样的代码,但它有一个错误:
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
int retval = chooser.showOpenDialog(null);
String yourpath = "E:\\Programy Java\\Projekt_SR1\\src\\project_sr1";
File directory = new File(yourpath);
String[] myFiles;
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File directory, String fileName) {
return fileName.endsWith(".txt");
}
};
myFiles = directory.list(filter);
if(retval == JFileChooser.APPROVE_OPTION)
{
File myFile = chooser.getSelectedFile();
}发布于 2011-04-09 16:58:39
Here你会找到一些实用的例子。This也是在JFileChooser中使用FileFilter的一个很好的例子。
基本步骤是,您需要覆盖FileFilter类,并在它的accpet方法中编写自定义代码。上例中的accept方法是根据文件类型进行过滤:
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else {
String path = file.getAbsolutePath().toLowerCase();
for (int i = 0, n = extensions.length; i < n; i++) {
String extension = extensions[i];
if ((path.endsWith(extension) && (path.charAt(path.length()
- extension.length() - 1)) == '.')) {
return true;
}
}
}
return false;
}或者更容易使用的是FileNameFilter,它有accept方法和filename作为参数,所以你不需要手动获取它。
发布于 2011-04-09 17:09:39
试试这样的..。
String yourPath = "insert here your path..";
File directory = new File(yourPath);
String[] myFiles = directory.list(new FilenameFilter() {
public boolean accept(File directory, String fileName) {
return fileName.endsWith(".txt");
}
});发布于 2014-07-18 14:43:03
在JDK8 on words中,它就像这样简单
final String extension = ".java";
final File currentDir = new File(YOUR_DIRECTORY_PATH);
File[] files = currentDir.listFiles((File pathname) -> pathname.getName().endsWith(extension));https://stackoverflow.com/questions/5603966
复制相似问题