JavaでZIPファイルを解凍するサンプルコード

 Javaコード:
/**
* zipファイルを解凍
* @param zipFilePath-zipファイルパス
* @param targetPath-解凍場所
* @throws IOException
*/
public String unZip_Startnews24(String zipFilePath, String targetPath) throws IOException {
OutputStream os = null;
InputStream is = null;
ZipFile zipFile = null;
String resultPath = null;
try {
zipFile = new ZipFile(zipFilePath,"UTF-8″);
String directoryPath = “";
if (null == targetPath || “".equals(targetPath)) {
directoryPath = zipFilePath.substring(0, zipFilePath.lastIndexOf(“."));
} else {
directoryPath = targetPath;
}
Enumeration<ZipEntry> entryEnum = zipFile.getEntries();
if (null != entryEnum) {
ZipEntry zipEntry = null;
while (entryEnum.hasMoreElements()) {
zipEntry = (ZipEntry) entryEnum.nextElement();
if (zipEntry.isDirectory()) {
continue;
}
if (zipEntry.getSize() > 0) {
// ファイル
File targetFile = buildFile(directoryPath + File.separator + zipEntry.getName(), false);
if (zipEntry.getName().contains(“webapps") && “index.html".equals(targetFile.getName())) {
resultPath = targetFile.getAbsolutePath();
}
os = new BufferedOutputStream(new FileOutputStream(targetFile));
is = zipFile.getInputStream(zipEntry);
byte[] buffer = new byte[4096];
int readLen = 0;
while ((readLen = is.read(buffer, 0, 4096)) >= 0) {
os.write(buffer, 0, readLen);
}

os.flush();
os.close();
} else {
}
}
}
} catch (IOException ex) {
throw ex;
} finally {
if (null != zipFile) {
zipFile = null;
}
if (null != is) {
is.close();
}
if (null != os) {
os.close();
}
}
return resultPath;
}

/**
ファイルを作成
* @param fileName ファイル名 パス付け
* @param isDirectory パスかどうか判断
* @return
*/
public File buildFile(String fileName, boolean isDirectory) {
File target = new File(fileName);
if (isDirectory) {
target.mkdirs();
} else {
if (!target.getParentFile().exists()) {
target.getParentFile().mkdirs();
if (target.exists()) {
target.delete();
}
target = new File(target.getAbsolutePath());
}
}
return target;
}

関数説明:

1.java.util.zip.ZipFile
このクラスは、ZIPファイルからエントリを読み込むために使用します

2.public Enumeration<? extends ZipEntry> entries()
戻り値:ZIPファイルエントリの列挙

3.BufferedOutputStream
バッファリングされた出力ストリームを実装します。

 

Java

Posted by arkgame