我如何使用Java下载和解压缩zip存档?

时间:2015-02-27 17:12:16

标签: java file download zip extract

我为自己和我的一个朋友制作了一个小型JPanel工具,它上面有图像图标。它加载来自"图像"的图像。 user.home中的文件夹,但我希望它在打开时检查该目录是否存在,如果不存在,请下载包含该文件夹的zip存档,并将其解压缩到user.home。有些人告诉我它甚至不可能,但我认为不然。我无法想办法这样做。谁能帮我吗?

1 个答案:

答案 0 :(得分:2)

实际上非常简单,只需在项目中添加Apache Commons IO和zip4j作为依赖项,以便使用FileUtils和Zip实用程序。

你可以使用Maven或任何你想要的东西。

就像在三个步骤中拆分所需内容一样简单,检查目录是否存在,然后如果没有下载文件,则将其解压缩。

String home = System.getProperty("user.home");
File imagesPath = new File(home + "/Images");
boolean exists = imagesPath.exists();
if (!exists) {
    // create directory
    imagesPath.mkdir();
    // download
    String zipPath = home + "/Images.zip";
    FileUtils.copyURLToFile(new URL("http://url/Images.zip"), new File(zipPath));
    // unzip
    try {
         new ZipFile(zipPath).extractAll(home + "/Images");
    } catch (ZipException e) {
         // do something useful
         e.printStackTrace();
    }
}
相关问题