rekt0x
rekt0x

Reputation: 503

Java - Get string path of resource files

I want to access to get the string path to my resource key files. If I debug the project in eclipse, everything works like a charm but if I export the project to a runnable .jar file - the project can't access the key files because the path is wrong.

PUBLIC_KEY_PATH = "src/resources/public.key";
PRIVATE_KEY_PATH = "src/resources/private.key";

But how do I get the right path for the runnable .jar file? I don't want to get the URL or anything else - I want to get the string path.

I hope that someone can help me.


Solution:

public static String PUBLIC_KEY_PATH = "/resources/public.key";
public static String PRIVATE_KEY_PATH = "/resources/private.key";

I'm using an InputStream to read the file content:

InputStream in = ExampleClass.class.getResourceAsStream(PUBLIC_KEY_PATH);
ObjectInputStream oin = new ObjectInputStream(new BufferedReader(in));

There we go ;)

Upvotes: 0

Views: 5767

Answers (2)

Amareswar
Amareswar

Reputation: 2064

YOu can copy those keys into WEB-INF/classes and where ever you are loading those, call

this.getClass().getClassloader().getResourceAsStream(fileName).

Upvotes: 0

Eng.Fouad
Eng.Fouad

Reputation: 117665

You can get an inputStream from the file via Class#getResourceAsStream(). For example:

InputStream is = FooClass.class.getResourceAsStream("public.key");

where you save public.key file in the same directory FooClass.java FooClass.class is located in.

Upvotes: 3

Related Questions