2005/05
結局ZIP解凍も必要ってことで調べました。
ZipInputStreamでやるのとZipFileを使うのと方法は2つありました。
Webでアップロードされたファイルを解凍するときはストリームが入力
だからZipInputStream使うっきゃないね。んじゃ、ソース
package work;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
/**
* Zip解凍する
*
* java work.UnZip [入力ファイル名]
* @author yamarou
*/
public class UnZip {
/**
* Zip解凍する
* @param args 入力ファイル名
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String filename = args[0];
proccessUnZip1(filename);
proccessUnZip2(filename);
}
/**
* ZipInputStreamを使ってZip解凍する。
* @param filename ZIPファイル名
* @throws IOException 入出力エラー
*/
private static void proccessUnZip1(String filename) throws IOException {
ZipInputStream zis = new ZipInputStream(new FileInputStream(filename));
ZipEntry entry = null;
while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory()) {
new File(entry.getName()).mkdirs();
} else {
File parent = new File(entry.getName()).getParentFile();
if(parent != null){
parent.mkdirs();
}
FileOutputStream out = new FileOutputStream(entry.getName());
byte[] buf = new byte[1024];
int size = 0;
while ((size = zis.read(buf)) != -1) {
out.write(buf, 0, size);
}
out.close();
}
zis.closeEntry();
}
zis.close();
}
/**
* ZipFileを使ってZip解凍する。
* @param filename ZIPファイル名
* @throws IOException 入出力エラー
*/
private static void proccessUnZip2(String filename) throws IOException {
ZipFile zipFile = new ZipFile(filename);
Enumeration enumeration = zipFile.entries();
while (enumeration.hasMoreElements()) {
ZipEntry entry = (ZipEntry) enumeration.nextElement();
if (entry.isDirectory()) {
new File(entry.getName()).mkdirs();
} else {
File parent = new File(entry.getName()).getParentFile();
if(parent != null){
parent.mkdirs();
}
FileOutputStream out = new FileOutputStream(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();
}
}
}
}
実行
javac -d . UnZip.java
java work.UnZip C:\temp\abc.zip
C:\temp\abc.zipは自分の環境に置き換えてね。
カレントディレクトリに解凍されるはず。