1

I have an application which is using a java.util.Properties class to store settings in a file. I load the file this way:

props.load(new FileInputStream("c2c_stngs.prop"));

Everything works well in IDE, also works after building and double click on .jar file.

My problem starts when I try to run it in command line like this:

java -jar c:\Works\project.jar

It throws an error:

java.io.FileNotFoundException: c2c_stngs.prop (The system cannot find the file specified)

I have the c2c_stngs.prop file in the same folder as the .jar file. Also I've tried to run cmd as an Administrator, but still the same.

Mat
  • 202,337
  • 40
  • 393
  • 406
Igor Toma
  • 158
  • 1
  • 8

2 Answers2

3

This is because you are accessing your jar through a path. Try changing your script to something like:

C:
CD \Works
java -jar project.jar

That should work but is not a solution to your problem. If you expect your properties file to always reside where your jar file is then you need to locate your jar file. See Finding the path to a jar from a Class inside it? for that.

Something like:

File propertiesFile = new File("c2c_stngs.prop");
if ( !propertiesFile.exists() ) {
  // Wont work 'cause getLocation returns a URL but you get my drift.
  propertiesFile = new File(getLocation(this.class), propertiesFile);
}
Community
  • 1
  • 1
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • Thank, that was it, simple! You wont believe, I start looking into regedit to see if there are any extra argument that makes it work by double clicking on .jar ;) – Igor Toma Dec 17 '11 at 13:32
2

You're using a relative path to load your properties file. This means that the code expects the properties file to be in the directory from which you start the program. So, if you're in c:\ when launching java, the file must be in c:\, and not in the directory where the jar is.

If the properties are read_only, the file should be in the jar, and you should load it from the classpath using Class.getResourceAsStream(). If it's read/write, use an absolute path to load the file.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Thanks, I've thought about that, but I need to write is well. My deployment script is copying the jar to a certain directory, so I just hard-coded the path. – Igor Toma Dec 17 '11 at 13:35