1

I'm struggling to access stopwords.txt, a list of stopwords my StopWordRemover class is using. I can access it just fine using its relative path "./stopwords.txt" when I run StopWordRemover as a standalone class, but when I try to use it in the Play application I keep getting FileNotFound Exceptions.

I've also tried:

  • moving it into the public folder, and accessing it using controllers.routes.Assets.at(...)
  • moving it into the conf folder

^Neither worked.

Where am I going wrong?

Relevant method:

private static void initStopWordList() {
        if (stopWords == null) {
            stopWordFilePath = "/stopwords.txt";
            stopWords = new ArrayList<>();
            try {
                Stream<String> stream = Files.lines(Paths.get(stopWordFilePath));
                stream.forEach(stopWords::add);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

Directory path:

app/
    service/
        StopWordRemover
    stopwords.txt
Ben Lawton
  • 29
  • 3

1 Answers1

0

I put it in the config folder.

Then you need to get it as a Resource not a File:

In Scala, for example:

private val stream = getClass.getResourceAsStream("/stopwords.txt")

Here some other versions you can try:

getClass.getResourceAsStream("stopwords.txt") or on windows getClass.getResourceAsStream("\stopwords.txt")

From here getting-a-resource-file-as-an-inputstream-in-playframework:

class Controller @Inject()(env: Environment, ...){

  def readFile = Action {  req =>
    ...

    //if the path is bad, this will return null, so best to wrap in an Option
    val inputStream = Option(env.classLoader.getResourceAsStream("/stopwords.txt"))

    ...
  }
}
pme
  • 14,156
  • 3
  • 52
  • 95
  • Unfortunately that didn't work! `InputStream in = StopWordRemover.class.getClass().getResourceAsStream("/stopwords.txt");` assigns a null value to `in`'. – Ben Lawton Mar 29 '18 at 12:15
  • Strange, maybe the classloader is the Problem? I added some other versions to my answer. The only difference I see is that you get the ClassLoader from `StopWordRemover.class.getClass()` as I do from `getClass()` Just to be sure: `stopwords.txt` is in `conf`? – pme Mar 29 '18 at 13:23