Application wide properties file

A

Adam

Hi

I am just getting to grips with Java and am having some problems with
distributing my applications.

I have the application packaged as a jar file, this jar file uses a download
extension to reference another jar file (DB drivers). There is also a
properties file the the application relies on. This is an application wide
properties file (not user specific) so I don't want it in the users home
directory. I cannot find a reliable way of determining where this file is
from within the Java code. The File(path) constructor looks in the users
home dir and then the current directory. If someone executes the jar file
using java -jar D:\AppPath\App.jar I cannot specify a relative reference
path within the code that will reliably find this file.

This must be a common problem and there is probably a simple method for
solving this.

Can anyone help?

Thanks
Adam
 
S

SPG

Hi,

You can locate a file within the classpath using:

this.getClass().getResource("myFile.config")

which returns a URL to the File that was found.
You may then place the file anywhere in the class path and it'll be found.
I always pack my config files in the root of the classpath.. Makes it easier
to manage.

HTH

Steve
 
A

Adam

Thanks for the advice

The code to open the properties file is inside a package. The package is
inside a Jar file. I would like to place the properties file in a directory
below the one the jar file is in. I have tried to use the Class-Path token
in the Jar manifest, but I can't get a URL to the file unless it is in the
same directory as my jar file.
also
Is there an easy way to get a File object from a URL?

thanks
Adam
 
S

SPG

Hi Adam.

OK, If you want to create a file, then you cannot do this inside a JAR. I
don't think this is what you want to do anyway..
Here is a sample that finds a file on the class path and gets a File object
from the URL.

URL textFileURL = this.getClass().getResource("/test.txt");
String fileName = textFileURL.getFile();
System.out.println(fileName);
File f = new File(fileName);
System.out.println(f.getAbsolutePath());

You can also use this.getClass().getResourceAsStream() which gives you an
InputStream object for the file..

Hope this helps..

Steve
 
A

Adam

Thank you very much Steve.

That was a great help. I needed to get a File object because I want to be
able to change the properties and write them back to the file.

Thanks again. You're a genius.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top