简体   繁体   English

从相对路径读取(zip)文件

[英]Read (zip) file from relative path

I am trying to read a zip file, which is inside my plugin project. 我正在尝试读取一个zip文件,该文件位于我的插件项目中。 This is the file hierarchy: 这是文件层次结构:

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

Inside the resources directory there is a zip file myarchive.zip which I want to load. 在resources目录中,有一个要加载的zip文件myarchive.zip

This is how I tried to do it: 这是我尝试执行的操作:

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();
}

The file cannot be found ( FileNotFoundException ), which means, that something is wrong with the relative path. 找不到文件( FileNotFoundException ),这意味着相对路径出了问题。

What is the problem and how can I read the zip file? 有什么问题,我如何阅读该zip文件?

I suggest to: 我建议:

  • detect the location of your current main jar 检测您当前主缸的位置
  • from this location determine the installation root 从此位置确定安装根目录
  • from the location of the installation root determine the path of your ZIP file. 从安装根目录的位置确定您的ZIP文件的路径。

Also consider to use the NIO.2 File API for both working with paths and working with ZIP files (using the ZIP file system provider ). 同时考虑使用NIO.2 File API来处理路径和使用ZIP文件(使用ZIP文件系统provider )。

Depends on how you are running this, is this a standalone or inside tomcat or such? 取决于您如何运行它,这是独立的还是在tomcat之内?

Try adding a prefix "/" OR thsi should work 尝试添加前缀“ /”,否则应该起作用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM