パスワード付きのZipファイルをJavaで処理する必要性が出てきました。 普段は java.util.zip.ZipInputStream を使って↓のように実装しますが、
FileInputStream fis = new FileInputStream(ファイル名); ZipInputStream zis = new ZipInputStream(fis); InputStreamReader in = new InputStreamReader(zis, "UTF-8");
パスワード付きのzipは食えないじゃんて事で。 ググってたらStackOverFlowの↓に行き着いて How to use zip4j to extract an zip file with password protection ↓こんなドンピシャな返答が。。
Try the following and make sure you are using the most recent Zip4j library (1.3.1):
String source = "folder/source.zip"; String destination = "folder/source/"; String password = "password"; try { ZipFile zipFile = new ZipFile(source); if (zipFile.isEncrypted()) { zipFile.setPassword(password); } zipFile.extractAll(destination); } catch (ZipException e) { e.printStackTrace(); }
ということで、Zip4jのウェブサイトからjarをダウンロードします。 http://www.lingala.net/zip4j/download.php hogeっていうディレクトリに2つテキストファイル作って、 Lhaplusっていうソフトウエアでパスワード付きのzipにします。 ダウンロードしたzip4j_1.3.1.jarにクラスパス通して、ZipFileというクラスをインポートして 上記のStackOverFlowに載ってた例をまんまで叩いてみると、、、
import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; public class unzipper { public static void main(String args[]) { String source = "hoge.zip"; String destination = "dest/"; String password = "hoge"; try { ZipFile zipFile = new ZipFile(source); if (zipFile.isEncrypted()) { zipFile.setPassword(password); } zipFile.extractAll(destination); } catch (ZipException e) { e.printStackTrace(); } } }
狙った通りに解凍されてて、 中身もOKでした。 って事でZip4j便利ですね~。