2011-08-15 5 views
1

次のコードを使用してインターネットからファイルを解凍しようとしています。ファイルの1つ(「uq.class」)は、オンラインソースから解凍された後、約2kbのファイルサイズが失われています(元のファイルは10,084、解凍されたファイルは8,261です)。他のすべてのファイルは完全に問題なく、zipからuq.classファイルをコピーして手動で配置すると、完全に機能します。誰でも何が起こっているのか説明して修正を提供できますか?以下はコードの解凍部分です。URLからJava unzipがファイルに2kbを逃した

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

答えて

2

一見したところでコードに間違いはありません。しかし私がお勧めするのは、あなたのストリームをより安全に閉じることです。現在の実装では、同時に入出力ストリームを閉じると、closeステートメントは、ステートメントを読み書きできるように例外を引き起こす可能性があります。それらのいずれかが失敗すると、ファイルは開いたままになり、アプリケーションではファイル記述子が不足します。 finallyステートメントでクローズを行うほうが良いです。クローズされたと確信しています。

+0

また、アウトストリームを2回クローズします;) – Dorpsidioot

0

私はなぜサインインできないのかわかりませんが、問題を理解しました。私は馬の事の前にカート全体をやった。私は適切なファイルを抽出し、古いファイルを抽出したので、古いファイルを再統合しました。ウィンドウをプログラミングするのに5時間。児童、適切なプログラミングのアーキテクチャは頭痛のトンを覚えておいてください。

+0

母、これは典型的な午後の典型的なコーディングのようです。 – Dorpsidioot

関連する問題