java有效地获取文件大小

问题:

在谷歌搜索时,我发现使用java.io.File#length()可能很慢。
 FileChannel也有一个size()方法。
有没有一个有效的方式来获取文件大小的java?

回答:

嗯,我试着用下面的代码来测量它:
对于运行= 1和迭代= 1,URL方法是最快的次数,后跟通道。我用一些暂停运行这个约10次。所以一次访问,使用URL是我能想到的最快的方式:

LENGTH sum: 10626, per Iteration: 10626.0

CHANNEL sum: 5535, per Iteration: 5535.0

URL sum: 660, per Iteration: 660.0

对于运行= 5和迭代= 50,画面不同。

LENGTH sum: 39496, per Iteration: 157.984

CHANNEL sum: 74261, per Iteration: 297.044

URL sum: 95534, per Iteration: 382.136

文件必须缓存对文件系统的调用,而通道和URL有一些开销。
码:

import java.io.*;
import java.net.*;
import java.util.*;

public enum FileSizeBench {

LENGTH {
@Override
public long getResult() throws Exception {
File me = new File(FileSizeBench.class.getResource(
“FileSizeBench.class”).getFile());
return me.length();
}
},
CHANNEL {
@Override
public long getResult() throws Exception {
FileInputStream fis = null;
try {
File me = new File(FileSizeBench.class.getResource(
“FileSizeBench.class”).getFile());
fis = new FileInputStream(me);
return fis.getChannel().size();
} finally {
fis.close();
}
}
},
URL {
@Override
public long getResult() throws Exception {
InputStream stream = null;
try {
URL url = FileSizeBench.class
.getResource(“FileSizeBench.class”);
stream = url.openStream();
return stream.available();
} finally {
stream.close();
}
}
};

public abstract long getResult() throws Exception;

public static void main(String[] args) throws Exception {
int runs = 5;
int iterations = 50;

EnumMap durations = new EnumMap(FileSizeBench.class);

for (int i = 0; i < runs; i++) { for (FileSizeBench test : values()) { if (!durations.containsKey(test)) { durations.put(test, 0l); } long duration = testNow(test, iterations); durations.put(test, durations.get(test) + duration); // System.out.println(test + " took: " + duration + ", per iteration: " + ((double)duration / (double)iterations)); } } for (Map.Entry entry : durations.entrySet()) {
System.out.println();
System.out.println(entry.getKey() + ” sum: ” + entry.getValue() + “, per Iteration: ” + ((double)entry.getValue() / (double)(runs * iterations)));
}

}

private static long testNow(FileSizeBench test, int iterations)
throws Exception {
long result = -1;
long before = System.nanoTime();
for (int i = 0; i < iterations; i++) { if (result == -1) { result = test.getResult(); //System.out.println(result); } else if ((result = test.getResult()) != result) { throw new Exception("variance detected!"); } } return (System.nanoTime() - before) / 1000; } } [/code]     Code问答: http://codewenda.com/topics/python/
Stackoverflow: java get file size efficiently

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

44 − 38 =