为什么我的BufferedInputStream没有下载某些文件?

时间:2013-08-02 04:27:37

标签: java bufferedinputstream

这是我的代码。

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次并完全停止。

任何人都可以解释原因吗?

2 个答案:

答案 0 :(得分: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();

如果输出流未正确关闭,我看到的唯一可能的故障是。可能无法将文件刷新到磁盘中。

答案 1 :(得分:0)

            URL url = new URL(logoPath);
            in = new BufferedInputStream(url.openStream());
            while (true) {

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

file size = app.getCoversize();