如何在 Java 中重试打开属性文件

发布于 2024-08-30 06:12:05 字数 112 浏览 3 评论 0 原文

我试图通过将线程挂起 x 秒并重新读取文件来处理 Java 中的 FileNotFoundException。这背后的想法是在运行时编辑属性。

问题是程序直接终止了。知道如何实现这个解决方案吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

寒冷纷飞旳雪 2024-09-06 06:12:05

有一个古老的秘诀,最初由 Bjarne Stroustroup 为 C++ 编写,现已移植到 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
    }
  }
}

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
    }
  }
}
旧情勿念 2024-09-06 06:12:05

循环加载文件,并在成功读取文件后设置条件所依赖的变量。在循环内使用 try-catch 块并在 catch-块中进行等待。

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.

你曾走过我的故事 2024-09-06 06:12:05

一些代码片段会很有用,但以下之一可能会出现问题:

  • 您的代码成功捕获第一个 FileNotFoundException,但唤醒后代码无法成功处理第二
  • 个异常 正在抛出另一个未处理的异常。尝试使用 catch (Exception e) 暂时包装有问题的代码,以查看抛出的异常
  • 您用来编辑文件的程序正在“锁定”属性文件,并可能阻止 Java 访问代码。

祝你好运

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

勿忘初心 2024-09-06 06:12:05

如果从未捕获到异常,则线程将终止。如果这是您的主线程,则应用程序结束。尝试以下操作:

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

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(...);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文