Zom*_*ian 1 java exception-handling
我正在运行以下代码来尝试从文本文件中读取.我对java很新,并且一直在尝试为自己创建项目.以下代码稍微修改了我最初发现的尝试和读取文本文件但由于某种原因它每次都捕获异常.它试图读取的文本文件只显示"hello world".我认为一定不能找到文本文件.我把它放在与源代码相同的文件夹中,它出现在源包中(我正在使用netbeans btw).它可能只需要以不同的方式导入,但我找不到任何进一步的信息.如果我的代码在这里是相关的,它在下面.
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");
}
}
Run Code Online (Sandbox Code Playgroud)
catch街区的右支撑是错位的.把它移到下面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
}
Run Code Online (Sandbox Code Playgroud)
作为防御性编程问题(至少在Java 7之前),您应该始终关闭finally块中的资源:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是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();
}
}
Run Code Online (Sandbox Code Playgroud)