0

Hi i have made a small program that reads a config file. This file is stored outside the actual jar file. On the same level as the jarfile actually. When i start my program from a commandline in the actual directory (ie. D:\test\java -jar name.jar argument0 argument1) in runs perfectly.

But when i try to run the program from another location then the actual directory i get the filenotfound exception (ie. D:\java -jar D:\test\name.jar argument0 argument1).

The basic functionality does seem to work, what am i doing wrong?

As requested a part of the code:

public LoadConfig() {
    Properties properties = new Properties();

    try {
        // load the properties file
        properties.load(new FileInputStream("ibantools.config.properties"));

    } catch (IOException ex) {
        ex.printStackTrace();
    } // end catch

    // get the actual values, if the file can't be read it will use the default values.
    this.environment = properties.getProperty("application.environment","tst");
    this.cbc = properties.getProperty("check.bankcode","true");
    this.bankcodefile = properties.getProperty("check.bankcodefile","bankcodes.txt");
} // end loadconfig

The folder looks like this: enter image description here

This works: enter image description here

This doesn't: enter image description here

The jar doesn't contain the text file.

Mijno
  • 79
  • 1
  • 2
  • 12

2 Answers2

2

When reading a File using the String/path constructors of File, FileInpustream, etc.. a relative path is derived from the working directory - the directory where you started your program.

When reading a file from a Jar, the file being external to the jar, you have at least two options :

  1. Provide an absolute path: D:/blah/foo/bar
  2. Make the directory where your file is located part of the class path and use this.getClass().getClassLoader().getResourceAsStream("myfile")

The latter is probably more appropriate for reading configuration files stored in a path relative to the location of your application.

Bruno Grieder
  • 28,128
  • 8
  • 69
  • 101
1

There could be one more possibility:

If one part of your code is writing the file and another one is reading, then it is good to consider that the reader is reading before the writer finishes writing the file.

You can cross check this case by putting your code on debug mode. If it works fine there and gives you FileNotFoundException, then surely this could be the potential reason of this exception.

Now, how to resolve:

You can use retry mechanism something similar to below code block

if(!file..exists()){
    Thread.sleep(200);
}

in your code and change the sleep value according to your needs.

Hope that helps.!!

Ajay Sodhi
  • 111
  • 1
  • 2