Java文件读写:IOException处理示例
在Java中,进行文件读写操作时可能会抛出IOException。以下是一个简单的示例,展示了如何处理IOException。
- 文件写操作:
import java.io.*;
public class FileWriteExample {
public static void main(String[] args) {
// 创建一个Writer对象
try (PrintWriter writer = new PrintWriter("test.txt")) {
// 写入一些文本
writer.println("This is a test write operation.");
System.out.println("Text has been written successfully.");
} catch (IOException e) {
System.err.println("Error occurred while writing to file: " + e.getMessage());
// 在这里,你可以选择记录错误信息、优雅降级或者干脆抛出异常
}
}
}
- 文件读操作:
import java.io.*;
public class FileReadExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("test.txt")))) {
String line;
// 逐行读取文件内容
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
System.out.println("File has been read successfully.");
} catch (IOException e) {
System.err.println("Error occurred while reading from file: " + e.getMessage());
// 在这里,你可以选择记录错误信息、优雅降级或者干脆抛出异常
}
}
}
在这个示例中,我们处理了 IOException。如果在读写文件时出现这类异常,我们会捕获它并根据需要进行适当的错误处理。
还没有评论,来说两句吧...