java.io.FileNotFoundException: nlpmodel/en-token.bin (No such file or directory)

27 Views Asked by At

I have a Java project. I need to use 3 files (pre-trained models) to use a tool (via API). The project works fine when I run it from the IntelliJ Idea. But if I make a jar file and execute the jar file from the terminal, I get the following exception. The structure of the project is also attached. The code sample is in the following.

private TokenizerME tokenizerProvider() throws IOException {
    
    InputStream inputStreamTokenizer = null;
    try {
      inputStreamTokenizer = new FileInputStream("nlpmodel/en-token.bin");
    } catch (FileNotFoundException e) {
      throw new RuntimeException(e);
    }
    TokenizerModel tokenModel = new TokenizerModel(inputStreamTokenizer);
    TokenizerME tokenizer = new TokenizerME(tokenModel);
    return tokenizer;

}

The exception:

Error: java.io.FileNotFoundException: nlpmodel/en-token.bin (No such file or directory)

project structure

I have already tried to use the following approach but it is not working.

URL url = getClass().getClassLoader().getResource("nlpmodel/en-token.bin");
inputStreamTokenizer = new FileInputStream(url.getFile());

Any suggestion will be highly appreciated. Thanks in advance.

1

There are 1 best solutions below

0
Jens On

The correct approach is to use

InputStream stream= getClass().getResourceAsStream("/nlpmodel/en-token.bin");

Pay special attention to the shash (/) at the beginning of the filename