我知道我可以使用FileFilter接口来做我想做的事情,但是我有一个练习,它要求我使用FileNameFilter实现按大小过滤文件。
这里有一个简单的代码,我给出了一个目录,代码应该从技术上过滤这个目录中的文件,并且只给出以".exe“结尾并且具有特定大小的文件。但是,我无法使用FileNameFilter进行大小筛选,因为它检查我发送的目录的大小,而不是其中的文件。
我对FileNameFilter的实现:
import java.io.File;
import java.io.FilenameFilter;
public class MyFileFilter implements FilenameFilter {
private String x;
private int size;
public MyFileFilter(String x, int size){
this.x = x;
this.size = size;
}
@Override
public boolean accept(File dir, String name) {
//i can't use the dir.length because it checks the size of the directory and not the inside files
return name.endsWith(x); // && dir.length() == size;
}
}主要如下:
File f = new File("C:\\Users\\Emucef\\Downloads\\Programs");
MyFileFilter mff = new MyFileFilter(".exe", 9142656);
File[] list = f.listFiles(mff);因此,基本上问题是:是否有一种方法可以使用FileNameFilter按大小过滤文件,如果是的话,如何过滤?
发布于 2018-10-22 11:07:17
试试这个:
@Override
public boolean accept(File dir, String name) {
File file = new File(dir, name);
return name.endsWith(x) && file.length() == size;
}发布于 2018-10-22 11:10:06
@Override
public boolean accept(File dir, String name) {
//i can't use the dir.length because it checks the size of the directory and not the inside files
if(name.endsWith(x))
{
File f = new File(dir.getPath(), name);
return f.length() == size;
}
return false;
}发布于 2018-10-22 11:09:10
您可以扩展您的类来检查它:
static class MyFileFilter implements FilenameFilter {
private String x;
private int size;
public MyFileFilter(String x, int size){
this.x = x;
this.size = size;
}
@Override
public boolean accept(File dir, String name) {
try {
return (name.endsWith(x) && Files.size(Paths.get(dir.getPath(), name)) == size);
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
}java.nio.file.Path是更现代的java.nio.file库的一部分,它完成了java.io.File所做的一切。
建议将java.nio.file.Path用于新项目。
https://stackoverflow.com/questions/52927587
复制相似问题