我正在运行以下代码来尝试读取文本文件。我是 java 的新手,一直在尝试为自己创建项目来练习。以下代码对我最初发现的尝试读取文本文件的代码稍作修改,但由于某种原因,它每次都会捕获异常。它试图读取的文本文件只显示“hello world”。我假设它一定找不到文本文件。我把它放在与源代码相同的文件夹中,它出现在源代码包中(顺便说一句,我使用的是 netbeans)。它可能只需要以不同的方式导入,但我找不到任何进一步的信息。如果我的代码与此处相关,则在下方。
package stats.practice;
import java.io.*;
import java.util.Scanner;
public final class TextCompare {
String NewString;
public static void main() {
try {
BufferedReader in = new BufferedReader(new FileReader("hello.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
}
System.out.println("Error");
}
}
最佳答案
catch
block 中的右括号放错了地方。将其移至 System.out.println("Error");
下方。
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new FileReader("hello.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) { // <-- from here
System.out.println("Error");
// or even better
e.printStackTrace();
} // <-- to here
}
作为防御性编程(至少在 Java 7 之前),您应该始终在 finally
block 中关闭资源:
public static void main(String[] args) {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("hello.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {}
}
// or if you're using Google Guava, it's much cleaner:
Closeables.closeQuietly(in);
}
}
如果您使用的是 Java 7,则可以通过 try
-with-resources 利用自动资源管理:
public static void main(String[] args) {
try (BufferedReader in = new BufferedReader(new FileReader("hello.txt"))) {
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
关于java - 为什么我要捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8639881/