我有一個問題,我似乎無法解決... 我做了一個文件的http下載,但在服務器和客戶端上的文件的CRC32做不匹配。此外,該文件有不同的大小,所以顯然我必須做錯了什麼......當我通過Firefox下載時,文件大小沒問題......所以我猜這是在客戶端代碼中的某處。Java http下載損壞文件
我已經找到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);
}
}
如果您不將此設爲社區wiki,您可能會收到更多回復。 – 2009-01-28 13:39:46