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

Javaコード

public String unrar(String sourceRar, String destDir) throws Exception {

String resultPath = null;
Archive a = null;
FileOutputStream fos = null;
try {
a = new Archive(new File(sourceRar));
if (null == destDir || “".equals(destDir)) {
destDir = a.getFile().getParentFile().getAbsolutePath();
}
FileHeader fh = a.nextFileHeader();
while (fh != null) {
if (!fh.isDirectory()) {
// destDirName と destFileNameを取得
String compressFileName = “";
if (fh.isUnicode()) {
compressFileName = fh.getFileNameW().trim();
} else {
compressFileName = fh.getFileNameString().trim();
}
String destFileName = “";
String destDirName = “";
//Windows以外のOS
if (File.separator.equals(“/")) {
destFileName = destDir +File.separator+ compressFileName.replaceAll(“\\\\", “/");
destDirName = destFileName.substring(0, destFileName.lastIndexOf(“/"));
// WindowsのOS
} else {
destFileName = destDir + compressFileName.replaceAll(“/", “\\\\");
destDirName = destFileName.substring(0, destFileName.lastIndexOf(“\\"));
}

// フォルダを作成
File dir = new File(destDirName);
if (!dir.exists() || !dir.isDirectory()) {
dir.mkdirs();
}
File destFile=new File(destFileName);
// ファイルを解凍
fos = new FileOutputStream(destFile);
if (“index.html".equals(destFile.getName())) {
resultPath = destFileName;
}
a.extractFile(fh, fos);
fos.close();
fos = null;
}
fh = a.nextFileHeader();
}
a.close();
a = null;
} catch (Exception e) {
throw e;
} finally {
if (fos != null) {
try {
fos.close();
fos = null;
} catch (Exception e) {
e.printStackTrace();
}
}
if (a != null) {
try {
a.close();
a = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
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;
}

Java

Posted by arkgame