代码之家  ›  专栏  ›  技术社区  ›  user697911

如何通过具有相对路径的getresourceasstream读取zip文件?

  •  0
  • user697911  · 技术社区  · 6 年前

    我曾经使用此方法读取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文件?

    1 回复  |  直到 6 年前
        1
  •  0
  •   user697911    6 年前

    您可以用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();
            }
    

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

    怎么了?紫坪铺的包装真的管用吗?