使用Java访问类路径中特定文件夹中的文件 [英] Accessing files in specific folder in classpath using Java

查看:256
本文介绍了使用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访问类路径中特定文件夹中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆