gpt4 book ai didi

java - 如何合并两个文本文件中的数据

转载 作者:行者123 更新时间:2023-11-30 11:13:04 32 4
gpt4 key购买 nike

我有两个相关的文本文件,例如 data1.txt 和 data2.txt。我想合并这两个文件以创建 result.txt。知道如何解决这个问题吗?

数据1.txt

books, 3
Shelf, 5
groceries,6
books, 1
Shelf, 2

数据2.txt

books,2
shelf,3
groceries,1

结果.txt

books, 3, 2
Shelf, 5,3
groceries,6,1
books, 1,2
Shelf, 2, 3

最佳答案

这是给你的一个例子。首先你需要从 data2 文本文件向 2d list 添加值。然后当 file2 中的行为 null 时,你可以从中获取相对于它的文本的映射值列表。所以我有一个方法可以返回一个字符串的映射值。代码比我想象的要长。我在这里只发布相关的方法。 This is link to complete class file

public void marged(){
try {
BufferedReader br1 = null;
BufferedReader br2 = null;

String line1;
String line2;
ArrayList<ArrayList<String>> arrayList = new ArrayList<>();

br1 = new BufferedReader(new FileReader("C:\\Users\\Madhawa.se\\Desktop\\workingfox\\data1.txt"));
br2 = new BufferedReader(new FileReader("C:\\Users\\Madhawa.se\\Desktop\\workingfox\\data2.txt"));

while ((line1 = br1.readLine()) != null) {

String[] split1 = line1.split(",");

String line1word = split1[0].trim();
String line1val = split1[1].trim();

line2 = br2.readLine();

if (line2 != null) {
String[] split2 = line2.trim().split(",");

String line2word = split2[0].trim();
String line2val = split2[1].trim();

ArrayList<String> list = new ArrayList();
list.add(line2word);
list.add(line2val);
arrayList.add(list);

if (line1word.equalsIgnoreCase(line2word)) {
String ok = line1word + "," + line1val + "," + line2val;
System.out.println(ok);
}

} else {
String ok = line1word + "," + line1val + "," + doesexist(arrayList, line1word);
System.out.println(ok);
}

}

} catch (Exception ex) {
ex.printStackTrace();
}
}

这是方法返回映射值

public String doesexist(ArrayList<ArrayList<String>> arrayList, String s) {

for (int i = 0; i < arrayList.size(); i++) {
String get = arrayList.get(i).get(0);
if (get.trim().equalsIgnoreCase(s.trim())) {
return arrayList.get(i).get(1);
}
}
return "-1";
}

输出>>

books,3,2
Shelf,5,3
groceries,6,1
books,1,2
Shelf,2,3

关于java - 如何合并两个文本文件中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26552624/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com