Java程序因打印线而减慢

时间:2014-02-10 22:56:57

标签: java inputstream

您好我有一个脚本,从网上下载文件,同时打印出进度。问题在于打印出进度的行减慢了程序的速度,有没有办法阻止它?

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();
    }
}
}

4 个答案:

答案 0 :(得分:2)

尝试仅打印每个第n个循环。

if(done % 10 == 0) System.out.println(progress);

答案 1 :(得分:2)

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

如果您想/需要打印进度,请为一堆KB读取,通常每4 KB。您可以使用byte[] buffer来读取和写入流中的数据。

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);
        }
    }
}

答案 2 :(得分:1)

只有在(done % 100 == 0)允许的情况下才能打印该行。

此外,您可以使用缓冲的阅读方式,这将加快程序的速度。

答案 3 :(得分:1)

建议:不要在循环的每次迭代中打印进度。使用计数器,确定合理的频率,修改计数器的数字,然后以所选频率打印进度。