views:

56

answers:

1

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?

+4  A: 

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();
   }
}
Itay
Looks promising but is this how you do this? This should be a pretty common problem with deployments. I am just wondering if this is the best practice for it.
Ritesh M Nayak
Yes. This method works perfectly. Thanks!
Ritesh M Nayak