How do I read a file from a package - something like a resource bundle in Java

自古美人都是妖i 提交于 2019-12-13 04:37:45

问题


I have a words.txt file that I have put in a particular java package and would need to read it from that same location. I do not control the deployment, so I don't know where the packages will be deployed.

Example location: com/example/files/words.txt .

I know how to use the ResourceBundle class to read properties file from the package hierarchy rather than a relative/absolute path. like ResourceBundle.getBundle(com.example.files.words) Is there something similar for general files so that I can read it from the package hierarchy rather than some absolute/relative path?


回答1:


You can use the getResourceAsStream() method (defined at class Class) to retrieve resources from the class-path. If class WordReader is located in package com.example then the path to the resource file should be files/words.txt

package com.example;

public class WordReader {

   public void readWords() {
     InputStream is = getClass().getResourceAsStream("files/words.txt");
     StringBuilder sb = new StringBuilder();
     for(Scanner sc = new Scanner(is); sc.hasNext(); )  
         sb.append(sc.nextLine()).append('\n');

     String content = sb.toString();
   }
}


来源:https://stackoverflow.com/questions/3036836/how-do-i-read-a-file-from-a-package-something-like-a-resource-bundle-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!