用java写编写一个程序,其功能是将两个文件的内容合并到一个文件中。 data1.txt【GBK】和data2.txt 【utf-8】 ---> result.txt【GBK】。
时间: 2024-02-22 19:56:06 浏览: 69
好的,以下是 Java 代码实现:
```java
import java.io.*;
public class MergeFile {
public static void main(String[] args) throws IOException {
String data1Path = "data1.txt";
String data2Path = "data2.txt";
String resultPath = "result.txt";
// 读取 data1.txt 文件
BufferedReader reader1 = new BufferedReader(new InputStreamReader(new FileInputStream(data1Path), "GBK"));
StringBuilder data1 = new StringBuilder();
String line;
while ((line = reader1.readLine()) != null) {
data1.append(line);
}
reader1.close();
// 读取 data2.txt 文件
BufferedReader reader2 = new BufferedReader(new InputStreamReader(new FileInputStream(data2Path), "UTF-8"));
StringBuilder data2 = new StringBuilder();
while ((line = reader2.readLine()) != null) {
data2.append(line);
}
reader2.close();
// 合并数据
String data = data1.toString() + data2.toString();
// 将合并后的数据写入 result.txt 文件
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resultPath), "GBK"));
writer.write(data);
writer.close();
}
}
```
以上代码中,使用了 `BufferedReader` 和 `BufferedWriter` 来读写文件。首先读取 `data1.txt` 文件时,使用 `InputStreamReader` 指定以 GBK 编码格式读取;而读取 `data2.txt` 文件时,以 UTF-8 编码格式读取。接着将两个文件的内容合并到一起,最后将合并后的数据以 GBK 编码格式写入 `result.txt` 文件中。
阅读全文