How to retry opening a properties file in Java
-
01-10-2019 - |
Question
I'm trying to handle an FileNotFoundException
in Java by suspending the thread for x seconds and rereading the file. The idea behind this is to edit properties during runtime.
The problem is that the programm simply terminates. Any idea how to realize this solution?
Solution
Do the file loading in a loop and set the variable the condition depends on after the file has been successfully read. Use a try-catch block inside the loop and do the waiting in the catch-block.
OTHER TIPS
There's a good-old 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
}
}
}
Some code snippets would be useful, but one of the following could be the problem:
- Your code successfully catches the first FileNotFoundException but after waking up the code does not successfully handle a second one
- Another exception is being thrown which is not being handled. Try temporarily wrapping the code in question with a
catch (Exception e)
to see what exception is being thrown - The program you use to edit the file is 'locking' the properties file and possbily preventing access by your Java code.
Good luck
If the Exception is never 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(...);
}