Java中读取两个文件的内容写入到一个文件中并去掉重复字段
时间: 2024-06-10 22:08:05 浏览: 19
你好啊!对于你的问题,我可以给你提供一个参考代码:
```java
import java.io.*;
import java.util.HashSet;
import java.util.Set;
public class MergeFiles {
public static void main(String[] args) throws IOException {
// 设置要读取的文件路径
String path1 = "path/to/first/file.txt";
String path2 = "path/to/second/file.txt";
// 设置要写入的文件路径
String outputPath = "path/to/output/file.txt";
// 创建输入流
BufferedReader reader1 = new BufferedReader(new FileReader(path1));
BufferedReader reader2 = new BufferedReader(new FileReader(path2));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputPath));
// 读取文件内容并去重
Set<String> set = new HashSet<>();
String line;
while ((line = reader1.readLine()) != null) {
set.add(line);
}
while ((line = reader2.readLine()) != null) {
set.add(line);
}
// 将去重后的内容写入到输出流中
for (String s : set) {
writer.write(s);
writer.newLine();
}
// 关闭流
reader1.close();
reader2.close();
writer.close();
}
}
```
希望能对你有所帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![xmind](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)