How do I read a file from a package - something li

2019-09-16 10:54发布

问题:

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();
   }
}