【问题标题】:How to read zip file through getResourceAsStream with relative path?如何使用相对路径通过 getResourceAsStream 读取 zip 文件?
【发布时间】:2019-04-22 10:22:20
【问题描述】:

我以前用这个方法读取我的maven的resources/目录下的文本文件,这样就可以使用相对路径了:

public static BufferedReader fileReaderAsResource(String filePath) throws IOException {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
        if (is == null) {
            throw new FileNotFoundException(" Not found: " + filePath);
        }
        return new BufferedReader(new InputStreamReader(is, DEFAULT_ENCODING));
    }

现在我需要读取 zip 文件,因为它的大小,我仍然想在我的“资源”目录中使用文件的相对路径。有没有办法做到这一点?

我有这种读取zip文件的方法,但它只能通过绝对路径读取文件:

public static BufferedReader fileZipReader(String fileName) throws IOException, URISyntaxException {
        URL zipUrl = IOUtils.class.getClassLoader().getResource(fileName);
        File zipFile = new File(zipUrl.toURI());
        ZipFile zip = new ZipFile(zipFile);
        for (Enumeration e = zip.entries(); e.hasMoreElements(); ) {
            ZipEntry zipEntry = (ZipEntry) e.nextElement();
            if (!zipEntry.isDirectory()) {
                return new BufferedReader(new InputStreamReader(zip.getInputStream(zipEntry)));
            }
        }
        throw new FileNotFoundException("File not found: " + fileName);
    }

如何通过我的标准 maven 资源/目录的相对路径读取 zip 文件?

【问题讨论】:

  • File zipFile = new File(zipUrl.toURI()); File 不能表示指向 Zip 条目的 URL。如果代码确实需要一个文件,那么首先需要将信息提取到一个文件中。

标签: java maven zip inputstream


【解决方案1】:

您可以使用 ZipInputStream 包装 InputStream,即:

InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
if (is == null) {
    throw new FileNotFoundException(" Not found: " + filePath);
}
ZipInputStream zis = new ZipInputStream(is);

编辑:

使用上面命名为“fileReaderZipAsResource”的方法,我正常读取文件:

try {
            BufferedReader br = fileReaderZipAsResource(qaFilePath);
            String line;
            while ((line = br.readLine()) != null) {
                if (line.isEmpty()) {
                    throw new RuntimeException("Invalid entry ... 2");
                }
                line = line.trim();
                textKGKB.add(line);
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

但是调试显示程序没有进入循环。它只是通过循环并继续逻辑,也不会引发异常。我的文本文件是一个用制表键分隔的 4 列文本文件。我只是将其压缩并命名为 xyy.zip,然后将其作为参数传递给上面的方法。

有什么问题? ZipInputStream 的封装真的有效吗?

【讨论】:

  • 我试过了,但没有用。我所做的只是简单地压缩文本文件并使用这种方法。请查看我的编辑。
  • 你能发布你的文件吗?
猜你喜欢
  • 1970-01-01
  • 2018-11-10
  • 1970-01-01
  • 1970-01-01
  • 2015-07-03
  • 2019-05-16
  • 2013-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多