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

时间:2018-04-05 04:21:06

标签: java

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'是我'resource'目录下的相对路径:

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'以使其正常工作?

1 个答案:

答案 0 :(得分:0)

创建一个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");
    }
}