Java中的IO操作:文件读写错误示例
在Java中进行文件读写时,可能会遇到各种错误。下面是一些常见的错误示例:
- FileNotFoundException:
当试图打开一个不存在的文件(如non_existent_file.txt
)时,会抛出这个异常。
try {
File file = new File("non_existent_file.txt");
FileReader reader = new FileReader(file);
// ...
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
- IOException:
这是一个父类,当任何与输入/输出操作相关的错误发生时,会抛出这个异常。
try {
File file = new File("test.txt");
FileOutputStream fos = new FileOutputStream(file);
// Write to file
} catch (IOException e) {
System.out.println("An error occurred during I/O: " + e.getMessage());
}
请注意,这些示例假设你正在尝试写入文件。读取文件也会遇到类似的问题。
还没有评论,来说两句吧...