我使用IntelliJ IDEA在Mac上进行编程,我正在编写程序以使用递归查找大文件(1GB)。这是我到目前为止编写的代码。
public class Exercise05 {
public static MyFilter myFilter = new MyFilter();
public static int count = 0;
public static void main(String[] args) throws FileNotFoundException {
File file = new File("/");
long startTime = System.currentTimeMillis();
findBigFile(file);
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
System.out.println(count);
}
public static void findBigFile(File file) throws FileNotFoundException {
if (file.isFile()) {
if (myFilter.bigFile(file)) {
System.out.println(file.getAbsolutePath());
System.out.println(file.length());
count++;
}
} else {
try {
if (file.listFiles().length > 0) {
File[] files = file.listFiles();
for (File file1 : files) {
findBigFile(file1);
}
}
} catch (NullPointerException ex) {
System.out.println(file.getAbsolutePath());
}
}
}
}
class MyFilter {
public boolean bigFile(File file) {
if (file.length() > (1024 * 1024 * 1024)) {
return true;
} else
return false;
}
}
以下是我的结果示例
/.DocumentRevisions-V100
/.fseventsd
/.Spotlight-V100
/.Trashes
/Applications/.Wineskin2
/Applications/AliWangwang.app/Contents/Frameworks/Sparkle.framework/Resources/fr.lproj/fr.lproj
/Applications/AliWangwang.app/Contents/Frameworks/Sparkle.framework/Resources/fr_CA.lproj
/Applications/AliWangwang.app/Contents/Frameworks/Sparkle.framework/Versions/A/Resources/fr.lproj/fr.lproj
/Applications/AliWangwang.app/Contents/Frameworks/Sparkle.framework/Versions/A/Resources/fr_CA.lproj
/Applications/AliWangwang.app/Contents/Frameworks/Sparkle.framework/Versions/Current/Resources/fr.lproj/fr.lproj
/Applications/AliWangwang.app/Contents/Frameworks/Sparkle.framework/Versions/Current/Resources/fr_CA.lproj
/Applications/leanote.app/Contents/Frameworks/Electron Framework.framework/Frameworks
/Applications/leanote.app/Contents/Frameworks/Electron Framework.framework/Libraries/Libraries
我调试了程序,发现在评估false
时,某些文件返回File.isFile()
,这很奇怪。它们是文件而不是文件夹,这导致程序执行else语句。为什么要这样做?
答案 0 :(得分:1)
javadoc声明:
public boolean isFile()
Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file.
Where it is required to distinguish an I/O exception from the case that the file is not a normal file, or where several attributes of the same file are required at the same time, then the Files.readAttributes method may be used.
Returns:
true if and only if the file denoted by this abstract pathname exists and is a normal file; false otherwise
因此,在您的情况下,该文件可能不是正常文件。
编辑:
因为isDirectory()只返回true,如果它是一个目录,你应该反转if else并改用file.isDirectory()。
答案 1 :(得分:1)
转换文件大小,然后进行比较以获取文件夹中的实际大文件。
double bytes = file.length();
double kilobytes = (bytes / 1024);
答案 2 :(得分:0)
您可以尝试使用File.isDirectory()
,看看它是否会返回相似的结果。