hellzone
hellzone

Reputation: 5236

How to set relative path with java?

I have a java application(Single jar file) and I want to get relative path to my conf file. Is there any way to get relative path to my conf file?

Here is my main class code; (under src\com\pro\code)

String confPath = "relative path to conf file";
BufferedReader input = new BufferedReader(
                         new InputStreamReader(
                           new FileInputStream(confPath), "UTF8"));

My config file is under

src\com\pro\conf 

path.

Upvotes: 1

Views: 786

Answers (3)

Olivier Grégoire
Olivier Grégoire

Reputation: 35427

Is your configuration file in your Jar file?

If yes, it's not a file, don't try accessing it like that.

Get it this way:

URL url = getClass().getClassLoader().getResource("/com/pro/conf/config.file.name");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));

Assuming that src is just a way to gather your sources together and not the name of a package. If it is part your package name, then use /src/com/pro/conf/config.file.name in getResource(...).

Upvotes: 1

freedev
freedev

Reputation: 30067

Try this:

new BufferedReader(
      new InputStreamReader(    
        this.getClass()
        .getResourceAsStream("com/pro/conf/filename"), "UTF8"));

Upvotes: 0

Steve Smith
Steve Smith

Reputation: 2270

If your conf file is where you say it is,

String confPath = "src/com/pro/code/conffile.conf";

should work, if your application's root directory contains the '/src' folder and the file itself is called conffile.conf.

Upvotes: 0

Related Questions