0

这是我的代码。

while ((count = in.read(data, 0, 16384)) != -1) // while there is still data from link to be read
{   
    download.removeMouseListener(m);
    /*speed.setText(String.valueOf(count));*/
    if (time >= time2 ){ // every second , set kb/s
        long initTimeInSeconds = initTime/1000000000;
        long currentTimeInSeconds = time/1000000000;
        speed.setText(String.valueOf((fout.getChannel().size() / 1024) / (currentTimeInSeconds-initTimeInSeconds) + "KB/s")); // set kb/s
        time2 = System.nanoTime() + 1000000000;
    }

    progress.setValue((int) fout.getChannel().size());//update progress bar
    fout.write(data, 0, count); // write the data to the file
    time = System.nanoTime();
} 

本质上,下载代码就是这样:

while ((count = in.read(data, 0, 16384)) != -1) // while there is still data from link to be read
{   
    fout.write(data, 0, count); // write the data to the file
    time = System.nanoTime();
} 

在哪里

byte data[] = new byte[16384];
BufferedInputStream in = null;
in = new BufferedInputStream(url.openStream());
int count = 0;

不知何故,这段代码没有下载某些文件,例如这个文件。 http://nmap.org/dist/nmap-6.40-setup.exe

while 循环刚开始时就消失了,它读取了 2 次并完全停止。

谁能解释为什么?

4

2 回答 2

2

这段代码对我来说很好用。下面的代码下载文件并写入磁盘。

            URL url = new URL("http://nmap.org/dist/nmap-6.40-setup.exe");
    url.openConnection();
    byte data[] = new byte[16384];
    BufferedInputStream in = null;
    in = new BufferedInputStream(url.openStream());
    int count = 0;
    OutputStream fout =  new FileOutputStream("C:/test.exe");
    while ((count = in.read(data, 0, 16384)) != -1) // while there is still data from link to be read
    {   
        fout.write(data, 0, count); // write the data to the file
        long time = System.nanoTime();
        System.out.println(time);
    } 
    fout.flush();
    fout.close();

我看到的唯一一种可能的故障是,如果输出流没有正确关闭。文件可能不会刷新到磁盘中的可能性。

于 2013-08-02T04:49:48.033 回答
0
            URL url = new URL(logoPath);
            in = new BufferedInputStream(url.openStream());
            while (true) {

                if (in.available() == Integer.parseInt(app.getCoversize()))
                    break;
            }

文件大小 = app.getCoversize();

于 2017-01-12T08:59:37.447 回答