3

我有一个问题,我似乎无法解决...我对文件进行了 http 下载,但服务器和客户端上文件的 CRC32 不匹配。另外,文件的大小不同,所以很明显我一定做错了什么……当我通过 Firefox 下载时,文件大小还可以……所以我猜它在客户端代码中的某个地方。

我在使用 Java 下载文件时已经发现Corrupt 文件,但这对我也没有帮助......

这是代码:

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);
  }
}
4

1 回答 1

6

您应该使用BufferedOutputStream而不是FileWriter/ BufferedWriter。通常,*Streams处理原始二进制数据,同时*Writers处理字符数据(这是对给定字符编码的原始二进制数据的解释)。

于 2009-01-28T13:38:41.077 回答