Turbojumala Turbojumala - 1 year ago 64
Java Question

Java Properties does not load when I call the program from another location

I have a program in which the properties file is in the same path as the program I'd like to run.

The properties file name is initialized at the start of the program with:

public static final String DEFAULT_PROPERTIES_FILE = "defaultProperties.properties";

The program runs perfectly when running it in the directory it itself is located in with:

java -jar program.jar

When running the program from another directory with:

java -jar path/program.jar

The program will not find the properties file and returns a

java.io.FileNotFoundException: defaultProperties.properties (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(FileInputStream.java:146) at java.io.FileInputStream.(FileInputStream.java:101) at com.Tool.parseArguments(Unknown Source)at com.Tool.main(Unknown Source)

Here's some more of the code. Sorry for being cautious with the sharing. I'm still very new and a little afraid of doing mistakes NDA-wise. I cut out the try-catches for readibility's sake :)

public static final String DEFAULT_PROPERTIES_FILE = "defaultProperties.properties";
private static final Properties DEFAULT_PROPERTIES = new Properties();


private static CommandLineBackedWithPropertiesFile parseArguments( String[] args )
CommandLineParser parser = new BasicParser();

CommandLine commandLine = null;
commandLine = parser.parse( OPTIONS, args );

Properties properties = new Properties( DEFAULT_PROPERTIES );
String propertiesFile =
commandLine.getOptionValue( OPTION_PROPERTIES_FILE,
properties.getProperty( OPTION_PROPERTIES_FILE ) );

if( StringUtils.isNotEmpty( propertiesFile ) )
properties.load( new FileInputStream( propertiesFile ) );

return new CommandLineBackedWithPropertiesFile( commandLine, properties );

I tried to look for a solution to this problem, but the closest I got to finding one was this. It doesn't actually address why the program won't run from anywhere else than it's own directory.

If anyone could help that'd be great! Thanks! :)

Answer Source

You have to specify the complete path of the property files. If you don't specify the path, then it will try to find file in same directory from which you started the jar. Hence FileNotFoundException.

One simple solution is - define property file's path as command line argument.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download