【问题标题】:How to get a BufferredReader from a zip file in resource directory?如何从资源目录中的 zip 文件中获取 BufferredReader?
【发布时间】:2018-04-05 04:21:06
【问题描述】:
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 文件,如何返回 BufferedReader?以下内容不起作用,因为 'fileName' 是我的 'resources' 目录下的相对路径:

public static BufferedReader fileZipReader(String fileName) throws IOException {
        ZipFile zip = new ZipFile(fileName);
        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);
    }

如何更改“fileZipReader”以使其工作?

【问题讨论】:

  • "is a relative path under my 'resources' directory" - 你的意思是它嵌入在你的应用程序二进制文件中,作为工作目录上下文中的独立目录存在?
  • src/main/resources
  • Out 所以它是一个嵌入式资源,这基本上使它成为一个 Zip 中的 Zip 文件。您将需要使用Class#getResourceClass#getResourceAsStream 并将文件解压缩到已知位置
  • 你能回答一下吗?谢谢你。根据 Shailesh 的建议,我总是得到空指针。
  • As a conceptual example ...你必须使用/main/resources作为你的路径

标签: java


【解决方案1】:

创建一个 URL 对象,提供 zip 文件的相对路径。

public class IOUtil {

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

    public static void main(String[] args) throws Exception {
        IOUtil util = new IOUtil();

        BufferedReader br = util.fileZipReader("dia/test.txt.zip");
    }
}

【讨论】:

  • 这里的“主要”是什么?
  • 使用您的起始或主要班级名称。如果没有主类,请在项目中使用任何公共类或接口名称。
  • 但是我得到了一个“zipUrl”的空指针异常,它是空的。我使用“URL zipUrl = IOUtils.class.getResource(fileName);” 'fileName' 是 src/main/resources/test.txt.zip 的相对路径
  • 您的意思是“/resources/...”。我的相对路径不包括这个“/resources/”部分。
  • 如果你的文件位于 src/main/resources/myfile.zip,你应该只给这个函数“myfile.zip”。你也在做同样的事情吗?
猜你喜欢
  • 1970-01-01
  • 2022-11-25
  • 1970-01-01
  • 2019-03-02
  • 2021-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多