【问题标题】:Read (zip) file from relative path从相对路径读取 (zip) 文件
【发布时间】:2015-11-19 13:32:12
【问题描述】:

我正在尝试读取一个 zip 文件,该文件位于我的插件项目中。这是文件层次结构:

my.super.project
  - Referenced Libraries
  - JRE System Library
  - src
  - binary
  - META-INF
  - resources

在资源目录中有一个压缩文件myarchive.zip,我想加载它。

这就是我尝试的方式:

byte[] buffer = new byte[1024];
try {
    ZipInputStream zis = new ZipInputStream(new FileInputStream(
            "resources/myarchive.zip"));
    // get the zipped file list entry
    ZipEntry ze = zis.getNextEntry();
    while (ze != null) {
        String fileName = ze.getName();
        File newFile = new File(OUTPUT_DIR
                + File.separator + fileName);
        // create all non exists folders
        new File(newFile.getParent()).mkdirs();
        FileOutputStream fos = new FileOutputStream(newFile);
        int len;
        while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }

        fos.close();
        ze = zis.getNextEntry();
    }
    zis.closeEntry();
    zis.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

找不到文件(FileNotFoundException),表示相对路径有问题。

有什么问题以及如何读取 zip 文件?

【问题讨论】:

    标签: java file eclipse-plugin zip inputstream


    【解决方案1】:

    我建议:

    • 检测当前主 jar 的位置
    • 从此位置确定安装根目录
    • 从安装根目录的位置确定您的 ZIP 文件的路径。

    还可以考虑使用 NIO.2 File API 来处理路径和 ZIP 文件(使用 ZIP file system provider)。

    【讨论】:

      【解决方案2】:

      取决于您如何运行它,这是独立的还是内部的 tomcat 或类似的?

      尝试添加前缀“/”或 thsi 应该可以工作

      URL url = this.getClass().getResource("/resources/myarchive.zip");
      ZipInputStream zis = new ZipInputStream(new FileInputStream( url.getFile() );
      

      【讨论】:

      • 不幸的是它不起作用。 FileNotFoundExceptionnew FileInputStream(url.getFile()) 抛出。我也试过"resources/myarchive.zip"作为路径,所以没有第一个/。有什么想法吗?
      猜你喜欢
      • 1970-01-01
      • 2019-04-22
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多