从URL解压的Java文件缺少2kb

从URL解压的Java文件缺少2kb,java,unzip,data-loss,Java,Unzip,Data Loss,我正在尝试使用以下代码从internet解压文件。在其中一个文件(“uq.class”)上,从在线源代码解压后,缺少约2kb的文件大小(原始文件是10084,解压后我得到8261)。所有其他文件似乎都很好,当我从zip中复制uq.class文件并手动将其放入时,它可以完美地运行。有人能解释一下发生了什么并提供解决方案吗?下面是代码的解压缩部分 public static File unpackArchive(URL url, File targetDir) throws IOException

我正在尝试使用以下代码从internet解压文件。在其中一个文件(“uq.class”)上,从在线源代码解压后,缺少约2kb的文件大小(原始文件是10084,解压后我得到8261)。所有其他文件似乎都很好,当我从zip中复制uq.class文件并手动将其放入时,它可以完美地运行。有人能解释一下发生了什么并提供解决方案吗?下面是代码的解压缩部分

public static File unpackArchive(URL url, File targetDir) throws IOException {
    if (!targetDir.exists()) {
        targetDir.mkdirs();
    }
    InputStream in = new BufferedInputStream(url.openStream(), 2048);
    // make sure we get the actual file
    File zip = File.createTempFile("arc", ".zip", targetDir);
    OutputStream out = new BufferedOutputStream(new FileOutputStream(zip),2048);
    copyInputStream(in, out);
    out.close();
    return unpackArchive(zip, targetDir);
}
public static File unpackArchive(File theFile, File targetDir) throws IOException {
    if (!theFile.exists()) {
        throw new IOException(theFile.getAbsolutePath() + " does not exist");
    }
    if (!buildDirectory(targetDir)) {
        throw new IOException("Could not create directory: " + targetDir);
    }
    ZipFile zipFile = new ZipFile(theFile);
    for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        File file = new File(targetDir, File.separator + entry.getName());
        if (!buildDirectory(file.getParentFile())) {
            throw new IOException("Could not create directory: " + file.getParentFile());
        }
        if (!entry.isDirectory()) {
            copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(file),2048));
        } else {
            if (!buildDirectory(file)) {
                throw new IOException("Could not create directory: " + file);
            }
        }
    }
    zipFile.close();
    theFile.delete();
    return theFile;
}

public static void copyInputStream(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int len = in.read(buffer);
    while (len >= 0) {
        out.write(buffer, 0, len);
        len = in.read(buffer);
    }
    in.close();
    out.close();
}
public static boolean buildDirectory(File file) {
    return file.exists() || file.mkdirs();
}

第一眼就看不出代码有任何错误。但是,我建议您做的是更安全地关闭您的流。在您当前的实现中,您可以同时关闭In和out流,close语句可能会导致异常,就像读和写语句一样!如果其中任何一个失败,您的文件将保持打开状态,应用程序的文件描述符将用完。你最好在最后声明中结束,这样你就可以确定他们已经结束了。

我不知道为什么我不能登录,但我已经解决了问题。我做了本末倒置的事。我提取了正确的文件,然后在上面提取了旧文件,所以我继续重新集成旧文件。5个小时的编程。记住,孩子们,正确的编程体系结构可以帮你省去很多麻烦。

此外,你还可以关闭两次分支;)哈哈,这看起来像是典型的周五下午的编码问题;)