1

我正在尝试使用以下代码从 Internet 解压缩文件。在其中一个文件(“uq.class”)上,从在线资源解压缩后,缺少大约 2kb 的文件大小(原始文件为 10,084,解压缩后得到 8,261)。所有其他文件似乎都很好,当我从 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();
}
4

2 回答 2

2

第一眼无法直接看出代码有什么问题。然而,我建议你做的是更安全地关闭你的流。在您当前的实现中,您同时关闭输入和输出流,关闭语句可能会导致异常,就像读写语句一样!如果其中任何一个失败,您的文件将保持打开状态,并且您的应用程序将及时用完文件描述符。您最好在 finally 语句中进行关闭,这样您就可以确定它们已关闭。

于 2011-08-15T10:13:29.340 回答
0

我不知道为什么我无法登录,但我发现了这个问题。我在马的事情之前做了整个车。我提取了正确的文件,然后在上面提取了旧文件,所以我一直在重新集成旧文件。5个小时的窗外编程。请记住,孩子们,正确的编程架构可以为您省去很多麻烦。

于 2011-08-16T01:35:08.247 回答