Java的IO操作:文件读写常见错误和案例
在Java中进行文件读写操作时,可能会遇到以下几种常见的错误:
- 文件不存在:
File file = new File("non_existent_file.txt");
if (!file.exists()) {
System.out.println("File does not exist.");
}
- 访问权限不足:
try {
// 没有读取文件的权限
BufferedReader reader = new BufferedReader(new FileReader("private_file.txt")));
System.out.println("Reading file...");
// 不会执行到这里的
} catch (Exception e) {
System.out.println("Permission denied: " + e.getMessage());
}
- 文件编码问题:
try {
File file = new File("non_utf8_file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file), "UTF-8"); // 使用正确的编码读取文件
System.out.println("Reading file...");
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println("Error reading file: " + e.getMessage());
}
IO操作未关闭资源:
try {
File file = new File("temp.txt");
FileWriter writer = new FileWriter(file); // 文件写入时忘记关闭
writer.write("Hello, World!");
writer.close(); // 关闭写入器,避免资源泄露
System.out.println("File written successfully.");
} catch (IOException e) {
System.out.println("Error writing file: " + e.getMessage());
}
以上就是Java文件读写操作中常见的错误及其案例。
还没有评论,来说两句吧...