【发布时间】:2019-08-09 16:25:47
【问题描述】:
此代码在复制大文件时运行速度越来越慢。我做错了吗?
InputStream ms2 = new BufferedInputStream(new FileInputStream("/home/fedd/Videos/homevid.mp4"));
OutputStream fos2 = new BufferedOutputStream(new FileOutputStream("testfile2.mp4", true));
try {
int byt;
int i = 0;
long time = System.currentTimeMillis();
while ((byt = ms2.read()) != -1) {
fos2.write(byt);
i++;
if (i > 100000) {
i = 0;
long took = System.currentTimeMillis() - time;
System.out.println("100000 bytes took " + took + " milliseconds which means " + (100000000 / took) + " bytes per second");
}
}
fos2.close();
ms2.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
我的 Java 是:
openjdk 10.0.2 2018-07-17 OpenJDK 运行时环境(构建 10.0.2+13-Ubuntu-1ubuntu0.18.04.4)
OpenJDK 64 位服务器虚拟机(内部版本 10.0.2+13-Ubuntu-1ubuntu0.18.04.4, 混合模式)
【问题讨论】:
-
什么是 ms2 (ms2.read())?检查你的while语句,我认为有一个错字。
-
您从循环的一开始就测量时间。您需要在打印后重置开始时间戳:
time = System.currentTimeMillis();. -
顺便说一句:在大多数磁盘/SSD 中,一段时间后性能显着下降是很正常的。这是由于内核级别甚至硬件级别的写入缓存。所以我也会简单地测试使用其他工具复制文件的速度……
-
我可以删除我的问题吗? :)
-
您应该使用 try with resources 语句(请参阅 docs.oracle.com/javase/tutorial/essential/exceptions/… )或关闭 finally 块中的流,否则它会由于打开的流而引入可能的内存泄漏。