Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 正在堆栈跟踪中捕获FileNotFound?_Java_Stack_Filenotfoundexception - Fatal编程技术网

Java 正在堆栈跟踪中捕获FileNotFound?

Java 正在堆栈跟踪中捕获FileNotFound?,java,stack,filenotfoundexception,Java,Stack,Filenotfoundexception,这似乎是一个奇怪的问题,但如果堆栈跟踪中存在filenotfoundexception,是否可以“捕获”(知道)?我这样问是因为我实现的类(不是我的)没有抛出异常,它捕获异常并打印堆栈跟踪 因此,换句话说,当堆栈跟踪中存在filenotfoundexception时,我是否可以显示带有自定义消息的JOptionPane 谢谢 我试过了: [不是打印堆栈跟踪的类:] catch ( Exception e ) { String trace = e.toString();

这似乎是一个奇怪的问题,但如果堆栈跟踪中存在filenotfoundexception,是否可以“捕获”(知道)?我这样问是因为我实现的类(不是我的)没有抛出异常,它捕获异常并打印堆栈跟踪

因此,换句话说,当堆栈跟踪中存在filenotfoundexception时,我是否可以显示带有自定义消息的JOptionPane

谢谢

我试过了:

[不是打印堆栈跟踪的类:]

    catch ( Exception e ) {
      String trace = e.toString(); 
        // there are better methods than toString() in newer JDK versions, 
        // but for now it should work
      if ( trace.toLowerCase().indexOf( "filenotfoundexception" ) >= 0 ) {
        // there is one
        JOptionPane....what ever you want...
      }
    }
更新:

您将不会得到被抑制的异常
但我强烈认为您的FileNot…异常不是其中之一…

这里有一种使用
System.setErr
和管道流的方法:
(完全有可能有更好的方法或者可以简化)

请注意,在同一个线程中连接流可能是不可取的,或者至少要非常小心,因为很容易陷入死锁

但更简单的是:

file.isFile() && file.canRead()

在函数调用之前,虽然不是100%可靠(在调用期间可能需要一个变通方法)。您可以事先检查该文件是否存在。是的,我可以,但为什么要运行代码两次呢?在运行代码之前,您可以进行一次合理快速的检查。不能保证一直工作,因为文件可以在检查和运行代码之间的毫秒内(或希望大约在这段时间内)删除(您可以通过某种方式锁定它作为一种变通方法),但可能比巫术更简单,可以重定向标准错误输出(如果可能的话)并对类似“FileNotFoundException”的内容进行字符串搜索。另一方面,请告诉编写该类的人请正确重写它(除非它不打算用作类库类):),是某个联机人员编写的,但无论如何,由于没有解决方案,我正在使用myFile.isFile()检查该文件&&myFile.canRead()。谢谢你的回答!我该把鱼放在哪里?正如我所说,在我的班上没有try/catch块,因为另一个班正在捕捉它,而不是抛出它。
file.isFile() && file.canRead()