使用Java访问类路径中特定文件夹中的文件

编程入门 行业动态 更新时间:2024-10-27 14:23:05
本文介绍了使用Java访问类路径中特定文件夹中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在com.example.resources包中读取一堆文本文件。我可以使用以下代码读取单个文件:

I want to read a bunch of text files in com.example.resources package. I can read a single file using the following code:

InputStream is = MyObject.class.getResourceAsStream("resources/file1.txt") InputStreamReader sReader = new InputStreamReader(is); BefferedReader bReader = new BufferedReader(sReader); ...

有没有办法获取文件列表然后传递每个元素到 getResourceAsStream ?

Is there a way to get the listing of file and then pass each element to getResourceAsStream?

编辑:关于ramsinb建议我改变了我的代码如下:

On ramsinb suggestion I changed my code as follow:

BufferedReader br = new BufferedReader(new InputStreamReader(MyObject.class.getResourceAsStream("resources"))); String fileName; while((fileName = br.readLine()) != null){ // access fileName }

推荐答案

如果您将目录传入 getResourceAsStream 方法,那么它将返回一个列出目录中的文件(或至少是它的流)。

If you pass in a directory to the getResourceAsStream method then it will return a listing of files in the directory ( or at least a stream of it).

Thread.currentThread().getContextClassLoader().getResourceAsStream(...)

我故意使用Thread来获取资源,因为它会确保我得到父类加载器。这在Java EE环境中很重要,但对于您的情况可能不会太多。

I purposely used the Thread to get the resource because it will ensure I get the parent class loader. This is important in a Java EE environment however probably not too much for your case.

更多推荐

使用Java访问类路径中特定文件夹中的文件

本文发布于:2023-10-31 16:47:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1546685.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   路径   夹中   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!