Arthur
Arthur

Reputation: 1176

GetResource with google io Files leads to FileNotFoundException for file from jar root

Code

Files.toString(new File(Thread.currentThread().getContextClassLoader().getResource(
    "login_commands.json").getFile()), Charsets.UTF_8)

Exception

java.io.FileNotFoundException: file:\C:\application\target.jar!\login_commands.json (The filename, directory name, or volume label syntax is incorrect)

Jar structure

-- root

The code works well from IDE.

How read this file?

Upvotes: 0

Views: 121

Answers (1)

Radouane ROUFID
Radouane ROUFID

Reputation: 10813

Solution

Use

Thread.currentThread().getContextClassLoader().getResourceAsStream("login_commands.json")

Insteed of

Thread.currentThread().getContextClassLoader().getResource("login_commands.json").getFile()

Why ?

When you use getResource(), the classloader try to get your file from <JAR_FOLDER>/YOUR_JAR.jar!login_commands.json and this path is not valid to create a java.io.File and throws a FileNotFoundException

Note that your code works in IDE because your IDE have its own Classloader that, when you call getResource or getResourceAsStream, get the file from workspace/test/target/classes/login_commands.json which is a valid path to create a File.

Upvotes: 1

Related Questions