gpt4 book ai didi

java - 为什么我的 BufferedInputStream 不下载某些文件?

转载 作者:行者123 更新时间:2023-12-02 06:51:13 28 4
gpt4 key购买 nike

这是我的代码。

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

谁能解释一下为什么吗?

最佳答案

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

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

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

关于java - 为什么我的 BufferedInputStream 不下载某些文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18008786/

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