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 srccomprocode)

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

My config file is under

srccomproconf 

path.

Answer

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(...).

Leave a Reply

Your email address will not be published. Required fields are marked *