【问题标题】:Java http download corrupts fileJava http下载损坏文件
【发布时间】: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);
  }
}

【问题讨论】:

  • 如果你不把它变成一个社区维基,你可能会得到更多的回应。

标签: java http download


【解决方案1】:

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

【讨论】:

  • 现在我得到了至少相同大小的文件,谢谢你的提示。但是CRC校验还是失败了……
  • Firefox 下载是否提供相同的 CRC32?
  • 似乎是不同CRC32计算的问题,下载的文件现在是二进制文件与服务器上的文件相同...感谢到目前为止的帮助。我想我现在又在路上了 ;-)
  • 是的,我很害怕...有一堆 CRC32 公式。也许您可以尝试 MD5 或其他加密哈希。
  • 我明白了。我使用 CRC32 Java 标准实现。但是当我在服务器上创建 CRC32 时,我犯了同样的 Stream/Writer 错误……结果导致不同的 CRC32!非常感谢,我想我不会那么容易找到的......
猜你喜欢
  • 2014-08-09
  • 1970-01-01
  • 1970-01-01
  • 2018-04-08
  • 2011-04-20
  • 1970-01-01
  • 2015-07-14
  • 2015-07-16
  • 2017-12-04
相关资源
最近更新 更多