我想在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访问类路径中特定文件夹中的文件
发布评论