2005/11
以前、ZIP解凍を取り上げたのですが、日本語ファイル名だと
エラーになります。でも、どうせimport文を
java.util.zip.ZipInputStreamから
org.apache.tools.zip.ZipInputStreamに変えればいいんでしょ?!
と思っていたのですが、な、な、なんと、
「org.apache.tools.zip.ZipInputStreamがない!?」
org.apache.tools.zip.ZipEntry
と
org.apache.tools.zip.ZipFile
が辛うじてあったので、それを使うことにします。なので、
InputStreamを引数にする場合、内部で一旦ZIPファイルを吐き出して
org.apache.tools.zip.ZipEntryを使用して解凍する。っていう
効率の悪い方法をとる必要があります。
package work;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
/**
* 日本語ファイル名に対応したZip解凍のSample。<br>
* InputStreamが引数の場合、
* org.apache.tools.zip.ZipInputStreamがない為、
* 内部で一旦ZIPファイルを吐き出して
* org.apache.tools.zip.ZipEntryを使用して解凍する。
* @author yamarou
*/
public class UnZip2 {
public static void main(String[] args) throws IOException {
unZip("C:\\TEMP\\hoge.zip", "C:\\TEMP\\zipwork");
}
/**
* Zip解凍する。<br>
* 内部で一旦ZIPファイルを吐き出して
* org.apache.tools.zip.ZipEntryを使用して解凍する。
* @param in ZIPファイルの入力ストリーム
* @param outDir 解凍先ディレクトリ
* @throws IOException 入出力エラー
*/
public static void unZip(InputStream in, String outDir)
throws IOException {
String tmpFile = "C:\\TEMP\\zip";
FileOutputStream out = new FileOutputStream(tmpFile);
byte[] buf = new byte[1024];
int size = 0;
while ((size = in.read(buf)) != -1) {
out.write(buf, 0, size);
}
out.close();
unZip(tmpFile, outDir);
new File(tmpFile).delete();
}
/**
* Zip解凍する。
* @param filename ZIPファイル名
* @throws IOException 入出力エラー
*/
public static void unZip(String filename, String outDir)
throws IOException {
ZipFile zipFile = new ZipFile(filename, "MS932");
Enumeration enum = zipFile.getEntries();
while (enum.hasMoreElements()) {
ZipEntry entry = (ZipEntry) enum.nextElement();
if (entry.isDirectory()) {
new File(entry.getName()).mkdirs();
} else {
File parent =
new File(outDir + "/" + entry.getName()).getParentFile();
if (parent != null) {
parent.mkdirs();
}
FileOutputStream out =
new FileOutputStream(outDir + "/" + entry.getName());
InputStream in = zipFile.getInputStream(entry);
byte[] buf = new byte[1024];
int size = 0;
while ((size = in.read(buf)) != -1) {
out.write(buf, 0, size);
}
out.close();
in.close();
}
}
zipFile.close();
}
}
>unZip("C:\\TEMP\\hoge.zip", "C:\\TEMP");
C:\\TEMP\\hoge.zipを適当に作って実行してみてください。
C:\\TEMPに解凍されます。