我正在尝试使用Java中的DNS在目录中搜索最大的文件。我想知道是否有任何方法可以使我的find函数返回最大的文件,而不是更改静态File变量的值。
public class File {
static File result = null;
static long fileSize = 0;
public static void main(final String[] args) {
final File dir = new File("/home/onel/");
find(dir);
System.out.println(result.getAbsolutePath());
}
private static void find(File directory) {
if (directory.listFiles() != null) {
for (final File f : directory.listFiles()) {
if (f.isFile() && f.length() > fileSize) {
result = f;
fileSize = f.length();
} else if (f.isDirectory()) {
find(f);
}
}
}
}
}
将File result
作为参数传递,然后返回
public static void main(final String[] args) {
final File dir = new File("c:/Temp");
File result = null;
result = find(dir, result);
System.out.println(result.getAbsolutePath());
}
private static File find(File directory, File result) {
if (directory.listFiles() != null) {
for (final File f : directory.listFiles()) {
if (f.isFile() && f.length() > fileSize) {
result = f;
fileSize = f.length();
} else if (f.isDirectory()) {
return find(f, result);
}
}
}
return result;
}