利用文件字节流和文件字符流的构造方法创建对象,通过read和write方法对数据进行读取和写入 用Java语言实现写三个类
时间: 2024-12-14 13:27:36 浏览: 6
在Java中,我们可以创建文件字节流(如`FileInputStream`、`FileOutputStream`等)和文件字符流(如`FileReader`、`FileWriter`等)来处理二进制数据和文本数据。下面我会分别介绍如何创建这三个类,并演示如何使用它们进行读取和写入操作:
1. **FileInputStream** 和 **FileOutputStream**
```java
import java.io.*;
public class FileInputStreamExample {
public void readBytesFromFile(String filePath) {
try {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
// 对数据进行处理...
System.out.println("Read " + bytesRead + " bytes");
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeBytesToFile(String filePath, byte[] data) {
try {
File file = new File(filePath);
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.close();
System.out.println("Data written to file successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. **FileReader** 和 **FileWriter**
```java
import java.io.*;
public class FileReaderWriterExample {
public void readFileToString(String filePath) {
try {
File file = new File(filePath);
FileReader fr = new FileReader(file);
StringBuilder sb = new StringBuilder();
char c;
while ((c = fr.read()) != -1) {
sb.append(c);
}
String content = sb.toString();
fr.close();
System.out.println("Read file content: " + content);
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeFile(String filePath, String text) {
try {
File file = new File(filePath);
FileWriter fw = new FileWriter(file);
fw.write(text);
fw.close();
System.out.println("Wrote text to file: " + text);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这两个类中,`read`和`write`方法用于从文件读取或写入数据,而`close`方法用于关闭流以释放资源。
阅读全文