【问题标题】:Why is my BufferedInputStream not downloading certain files?为什么我的 BufferedInputStream 不下载某些文件?
【发布时间】:2013-08-02 04:27:36
【问题描述】:

这是我的代码。

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

谁能解释一下原因?

【问题讨论】:

    标签: java bufferedinputstream


    【解决方案1】:

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

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

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

    【讨论】:

    • 感谢您的回复,我发现问题出在我的学校网络上,显然我的应用程序不想使用它。可能是端口号,可以更改我下载文件的端口吗?
    • 您无法更改端口。服务器将不得不要求客户端更改端口,请注意客户端
    【解决方案2】:
                URL url = new URL(logoPath);
                in = new BufferedInputStream(url.openStream());
                while (true) {
    
                    if (in.available() == Integer.parseInt(app.getCoversize()))
                        break;
                }
    

    文件大小 = app.getCoversize();

    【讨论】:

    • 确定时间间隔 = getInterval() 文件大小 = app.getLogosize()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多