0
我正在从服务器上下载一个zip文件,但不断收到损坏的文件。我的连接速度很慢,并且我知道服务器会经常更新文件。这是为什么我得到损坏的文件?我会假设网络协议应该足够聪明以避免这种情况。在服务器上修改正在下载的文件时会发生什么情况?
private void downloadFile(String urlString, String fileName)
throws MalformedURLException, IOException {
InputStream input = new URL(urlString).openConnection().getInputStream();
FileOutputStream output = new FileOutputStream(fileName);
int bufferSize = 153600;
byte[] buffer = new byte[bufferSize];
int totalBytesRead = 0;
int bytesRead = 0;
while ((bytesRead = input.read(buffer)) > 0) {
output.write(buffer, 0, bytesRead);
buffer = new byte[bufferSize];
totalBytesRead += bytesRead;
}
output.close();
input.close();
}
谢谢!
网络协议与通过它发送的数据无关。这取决于服务器的实现。 – SLaks 2012-02-10 23:44:59
这与“网络协议”无关。我怀疑服务器是修改* .zip文件,而不是仅仅创建一个具有相同名称的新文件(这不会影响当前打开的文件句柄)。如果后者不正确...是的,那么,不要这样做。 – 2012-02-10 23:46:53
循环中的'new byte []'应该被删除。您可以使用像'org.apache.commons.io.StreamUtils.pipe(输入,输出)'这样经过验证的库。 – 2012-02-11 00:08:56