把目前写的Java程序内容在屏幕打印出来(主动检测异常处理)
时间: 2024-03-20 14:41:11 浏览: 20
好的,以下是一个简单的Java程序,可以将一个文件的内容读取并打印在屏幕上。程序中包含了主动检测异常处理的代码,能够捕获并处理可能出现的异常。
```java
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class PrintFileContent {
public static void main(String[] args) {
String fileName = "test.txt";
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + fileName);
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}
```
在上面的代码中,我们通过创建一个 `BufferedReader` 对象来读取文件内容,并在控制台上打印每一行。在 `try...catch` 块中,我们捕获了可能出现的 `FileNotFoundException` 和 `IOException` 异常,并在控制台上输出相应的错误信息。这样,在程序运行过程中,即使出现了异常,我们也能够及时地发现并处理它们。