Java中IO操作:文件读写及错误处理
在Java中,IO(Input/Output)操作主要包括文件的读写和相关的错误处理。
文件读写:
FileReader
和FileWriter
:这两个类是用于文本文件的读写。例如,创建一个文件并写入内容:
```java
// 创建一个文件对象
File file = new File(“example.txt”);
// 如果文件不存在,则创建它
if (!file.exists()) {file.createNewFile();
}
// 使用FileWriter写入内容
try (FileWriter writer = new FileWriter(file)) {String content = "This is an example";
writer.write(content);
} catch (IOException e) {
System.out.println("Error occurred while writing to file: " + e.getMessage());
}
BufferedReader
和PrintWriter
:这些类用于处理二进制文件。例如,读取和写入二进制数据:
```java
try (FileInputStream fis = new FileInputStream(“example.bin”);BufferedReader br = new BufferedReader(new InputStreamReader(fis)))) {
String line;
while ((line = br.readLine()) != null) {// 处理读到的行
System.out.println(line);
}
} catch (IOException e) {
System.out.println(“Error occurred while reading file: “ + e.getMessage());
}OutputStream
和InputStream
:这些类用于处理数据,但不直接操作文件。例如,写入和读取字节:try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ByteArrayInputStream bis = new ByteArrayInputStream("Hello, World!".getBytes())) {
byte[] bytes = bis.readAllBytes();
System.out.println("Read bytes: " + new String(bytes)));
bos.write("This will be appended.".getBytes());
byte[] appendedBytes = bos.toByteArray();
System.out.println("Appended bytes: " + new String(appendedBytes)));
} catch (IOException e) {
System.out.println("Error occurred while reading or writing bytes: " + e.getMessage());
}
}
错误处理:
try-catch
语句:用于捕获和处理可能抛出的异常。IOException
:Java中所有输入/输出操作可能会抛出此类异常。
示例:
import java.io.*;
// 文件读写时可能出现的错误
class FileOperationError extends IOException {
public FileOperationError(String message) {
super(message);
}
}
try {
// 创建一个文件对象
File file = new File("example.txt");
// 试图写入内容,可能会抛出FileNotFoundException
try (FileWriter writer = new FileWriter(file)) {
String content = "This is an example";
writer.write(content);
} catch (IOException e) {
System.out.println("Error occurred while writing to file: " + e.getMessage());
throw new FileOperationError("Failed to write to file due to I/O error", e);
}
// 试图读取文件,可能会抛出FileNotFoundException
try (BufferedReader reader = new BufferedReader(new FileReader(file)))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error occurred while reading from file: " + e.getMessage());
throw new FileOperationError("Failed to read from file due to I/O error", e);
}
} catch (FileOperationError e) {
System.out.println(e.getMessage());
// 如果需要,可以在此处进一步处理错误
}
这段代码展示了如何使用try-catch语句进行文件操作的错误处理。
还没有评论,来说两句吧...