【发布时间】:2009-01-28 13:35:04
【问题描述】:
我有一个问题,我似乎无法解决... 我对文件进行了 http 下载,但服务器和客户端上文件的 CRC32 不匹配。另外,文件的大小不同,所以显然我做错了什么......当我通过Firefox下载时,文件大小还可以......所以我猜它在客户端代码的某个地方。
我已经找到Corrupt file when using Java to download file,但这对我也没有帮助...
代码如下:
private void downloadJar(String fileName, long crc32Server) throws IOException {
System.out.println("Downloading file '" + fileName + "' from server '" + mServer + "'.");
HttpURLConnection sourceConnection = null;
BufferedInputStream inputStream = null;
BufferedWriter fileWriter = null;
long crc32Client;
try {
URL sourceURL = new URL(fileName);
try {
sourceConnection = (HttpURLConnection)sourceURL.openConnection();
}
catch (MalformedURLException exc) {
throw new RuntimeException("Configured URL caused a MalformedURLException: ", exc);
}
sourceConnection.setRequestProperty("Accept-Encoding", "zip, jar");
sourceConnection.connect();
inputStream = new BufferedInputStream(sourceConnection.getInputStream());
fileWriter = new BufferedWriter(new FileWriter(targetFolder + File.separator + fileName));
CRC32 crc32 = new CRC32();
for (int singleByte = inputStream.read(); singleByte != -1; singleByte = inputStream.read()) {
fileWriter.write(singleByte);
crc32.update(singleByte);
}
crc32Client = crc32.getValue();
}
finally {
if (inputStream != null) {
inputStream.close();
}
if (fileWriter != null) {
fileWriter.flush();
fileWriter.close();
}
if (sourceConnection != null) {
sourceConnection.disconnect();
}
}
if (crc32Client != crc32Server) {
// deleteFile(fileName);
throw new IOException("CRC32 did not match for file '" + fileName + "': " + crc32Client + "!="
+ crc32Server);
}
}
【问题讨论】:
-
如果你不把它变成一个社区维基,你可能会得到更多的回应。