java - 在 Java 中是否有 try/catch 的替代方法来打开文件?

标签 java c++ file exception-handling try-catch

我记得在我的 c++ 类中,我们会使用以下代码来处理打开文件时的错误:

ifstream in;
in.open("foo.txt");
if(in.fail()){
   cout << "FAILURE. EXITING..." << endl;
   exit(0);
}

现在我正在学习 java,我在使用 try/catch 语句时遇到了麻烦,因为当我创建一个扫描器来读取我的输入文件时,它不是' 在 try 代码块之外识别。 java 中是否有与fail()exit(0) 等效的方法,或者是否有更好的方法?

最佳答案

I'm having trouble using try/catch statements, because when I create a scanner to read my input file, it isn't recognized outside of that 'try' code block.

很好!您不应该在 try block 之外使用它。文件的所有相关处理都应该 try block 中,例如:

try (
    InputStream istream = new FileInputStream(/*...*/); // Or Reader or something
    Scanner scanner = new Scanner(istream)
    ) {
    // Use `scanner` here
}
// Don't use `scanner` here

(这是使用新的 try-with-resources。)

在上文中,我假设当您说 Scanner 时,您指的是 Scanner 类。

回答您的实际问题:不,这不是 Java 代码中的标准做法。 Java 拥抱异常。

关于java - 在 Java 中是否有 try/catch 的替代方法来打开文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27528900/

相关文章:

java - java如何解析像[new File ("filename.txt")]这样的相对路径?

java - Gradle - 很多模块

java正则表达式搜索替换问题

java - 是否可以在tomcat7中将 'http://localhost:8080/myapplication'更改为类似 'http://myApp/'的内容?

c++ - 如何修复只读对象中成员的错误分配?

android - 为 Android NDK 编译 C++11 源代码

c++ - 删除和修改 Boost MultiIndex 容器中的元素

regex - Mercurial/.hgignore - 如何忽略除文件夹内容之外的所有内容?

JavaFX 从文件读取抛出 "InvocationTargetException"?

java - 使用 Date API 的日期类的默认构造函数