0 votes
1 view
in Java by (10.2k points)

I am trying to get a path to a Resource but I have had no luck.

This works (both in IDE and with the JAR) but this way I can't get a path to a file, only the file contents:

ClassLoader classLoader = getClass().getClassLoader();

PrintInputStream(classLoader.getResourceAsStream("config/netclient.p"));

If I do this:

ClassLoader classLoader = getClass().getClassLoader();

File file = new File(classLoader.getResource("config/netclient.p").getFile());

The result is: java.io.FileNotFoundException: file:/path/to/jarfile/bot.jar!/config/netclient.p (No such file or directory)

Is there a way to get a path to a resource file?

1 Answer

0 votes
by (46.1k points)
This is deliberate. The contents of the "file" may not be available as a file. Remember you are dealing with classes and resources that may be part of a JAR file or other kind of resource. The classloader does not have to provide a file handle to the resource, for example the jar file may not have been expanded into individual files in the file system.

Anything you can do by getting a java.io.File could be done by copying the stream out into a temporary file and doing the same, if a java.io.File is absolutely necessary.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 11, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 13, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer
asked Sep 29, 2019 in Java by Shubham (3.9k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...