我该如何使用Java下载和解压缩zip档案



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

实际上很容易,只需在项目中添加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();
    }
}

最新更新