How to retry opening a properties file in Java

I am trying to process FileNotFoundException

in Java by pausing a thread for x seconds and re-reading a file. The idea is to edit properties at runtime.

The problem is that the program just exits. Any idea how to implement this solution?

+2


a source to share


4 answers


Loops to load a file and sets a variable whose condition depends on how the file was successfully read. Use a try-catch block inside a loop and wait in the catch block.



+1


a source


There's a good recipe, originally by Bjarne Stroustroup for C ++, ported here to Java:



Result tryOpenFile(File f) {
  while (true) {
    try {
      // try to open the file
      return result; // or break
    } catch (FileNotFoundException e) {
      // try to recover, wait, whatever
    }
  }
}

      

+3


a source


Some code snippets will be helpful, but one of the following problems could be a problem:

  • Your code will successfully catch the first FileNotFoundException, but upon waking up, the code does not successfully handle the second
  • Another exception is thrown and not handled. Try temporarily wrapping the code in question with a catch (Exception e)

    to see which exception is thrown.
  • The program you use to edit the file is to "lock" the properties file and prevent access by your Java code.

Good luck.

0


a source


If the exception never gets caught, the thread is terminated. If this is your main thread, the application ends. Try the following:

try
{
   props.load(...);
}
catch (FileNotFoundException ex)
{
   Thread.sleep(x * 1000);
   props.load(...);
}

      

-2


a source







All Articles