简体   繁体   English

如何从资源目录中的zip文件获取BufferredReader?

[英]How to get a BufferredReader from a zip file in resource directory?

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

This works for non-zip file. 这适用于非zip文件。 But for zip file, how to return a BufferedReader? 但是对于zip文件,如何返回BufferedReader? The following doesn't work since 'fileName' is a relative path under my 'resources' directory: 由于'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);
    }

How to change the 'fileZipReader' to make it work? 如何更改“ fileZipReader”以使其正常工作?

Create a URL object giving a relative path to zip file. 创建一个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");
    }
}

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

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