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

用户名
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");
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何获取源目录中包含的文件?

获取资源目录中的文件名

忽略资源目录中的特定文件

如何在资源目录中的Java中创建文件

Android gradle:如何在 build.gradle 脚本中获取合并的资源目录?

Maven exec:java:如何打开和读取资源目录中的文件?

如何访问Java中调用程序的资源目录

如何在Laravel的资源目录中存储图像

如何从资源目录读取多个文件

如何从脚本本身中获取Bash脚本的源目录?

如何从脚本本身中获取Bash脚本的源目录?

如何访问我的 Maven Web 服务项目中资源目录中的文件?

如何在不提供绝对路径的情况下访问PyDev项目的资源目录中的文件?

如何在Install 4j中的资源目录中创建目录

列出sbt 1.2.8中资源目录中的文件

如何将资源目录以及Jar中所有包含的文件和子文件夹复制到另一个目录中

如何以编程方式获取资源目录路径

如何在PHP中获取zip文件的目录结构?

从Apache Spark Streaming上下文访问JAR中资源目录中的文件

Java项目:无法访问资源目录中的属性文件

使用Maven(使用Eclipse IDE)无法访问资源目录中的文件

从资源目录密钥库异常中读取的Java JKS文件

在ZIP文件中获取目录条目

Intellij Web 资源目录中的 Web Facets 错误

android中无效的资源目录名称

将资源目录包含到 Quarkus 目标输出中

ExternalProject错误:文件试图在源目录中创建目录

从资源目录读取文件的scala问题

无法从资源目录加载属性文件