gpt4 book ai didi

Java 程序因打印行而变慢

转载 作者:行者123 更新时间:2023-12-03 23:18:08 24 4
gpt4 key购买 nike

您好,我有一个脚本,可以从网上下载文件,同时打印出进度。问题是打印进度的那一行使程序变慢了很多,有什么办法可以阻止它吗?

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;


public class download {
public static void main(String[] args) {
try{
URL u = new URL("http://upload.wikimedia.org/wikipedia/commons/1/16/Appearance_of_sky_for_weather_forecast,_Dhaka,_Bangladesh.JPG");
FileOutputStream fos = new FileOutputStream("C://Users/xxx/Desktop/test.jpg");
InputStream is = u.openStream();

long size = u.openConnection().getContentLengthLong();
int data;
long done = 0;
while((data = is.read())!=-1){
double progress = (double) (done)/(double)(size)*100;
System.out.println(progress); // if we dont do this then then it completes fast
fos.write(data);
done++;
}
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
}

最佳答案

首先,每一次I/O操作都会有很高的开销。现在,您正在为读取的每个字节打印一条消息!(在 InputStream#read 中注明)。

如果您想要/需要打印进度,请为读取的一堆 KB 执行此操作,通常每 4 KB 执行一次。为此,您可以使用 byte[] 缓冲区 从流中读取和写入数据。

BufferedInputStream input = null;
BufferedOutStream output = null;
final int DEFAULT_BUFFER_SIZE = 4 * 1024;
try {
input = new BufferedInputStream(is, DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(fos, DEFAULT_BUFFER_SIZE);

byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
done += length;
double progress = (double) (done)/(double)(size)*100
System.out.println(progress);
}
} catch (IOException e) {
//log your exceptions...
} finally {
closeResource(output);
closeResource(input);
}

还有这个closeResource方法:

public void closeResource(Closeable resource) {
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
logger.error("Error while closing the resource.", e);
}
}
}

关于Java 程序因打印行而变慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21689655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com