Java中IO流操作问题:读写文件示例
在Java中,IO流主要用于处理输入输出。以下是一个读写文件的简单示例:
- 创建一个File对象:
```java
import java.io.File;
String fileName = “example.txt”; // 文件名
File file = new File(fileName); // 创建File对象
2. **检查文件是否存在**:
```java
if (!file.exists()) {
System.out.println("File does not exist.");
} else {
System.out.println("File exists.");
}
读取文件内容:
try {
String content = new String(file.readAllBytes()));
System.out.println("Content of file: " + content);
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
e.printStackTrace();
}
写入文件内容:
try {
String newData = "This is the new content.";
// 将字符串转换为字节数组
byte[] bytesToWrite = newData.getBytes();
// 写入新的内容到原文件
file.writeAll(bytesToWrite));
System.out.println("Content updated successfully.");
} catch (IOException e) {
System.out.println("Error updating file: " + e.getMessage());
e.printStackTrace();
}
以上就是Java中读写文件的基本示例。在实际开发中,可能会遇到更多错误和异常情况,需要进行适当的处理。
还没有评论,来说两句吧...