java - 如何从资源目录中的 zip 文件获取 BufferedReader?

标签 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”是我的“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”以使其正常工作?

最佳答案

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

关于java - 如何从资源目录中的 zip 文件获取 BufferedReader?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49664126/

相关文章:

java - 在 Spring bean 中定义枚举映射

java - 与 Java 7 相比,Java 8 ScriptEngine 的主要性能问题

java - revalidate()/repaint() 在 ActionListener 中不起作用

java - 在 Swing Java 中向 JList 添加元素

javascript - HTML+javascript还是javascript+jsp?

java - 类似的接口(interface)项目

java - 在 Firebase 数据库上写入用户单击 listView 项目上的按钮

java - C++ 到 Java 中的全局变量

java - 从浏览器打开 Android 应用

GetMethod 中的 Java 反射枚举类型