我有2个文件如下:
1.txt
first|second|third
fourth|fifth|sixth
2.txt
first1|second1|third1
fourth1|fifth1|sixth1
现在我想加入他们:
first|first1|second1|third1|second|third
fourth|fourth1|fifth1|sixth1|fifth|sixth
我尝试使用扫描仪但无法加入它们。任何建议。
Scanner scanner = new Scanner(new File(("F:\\1.txt")));
Scanner scanner2 = new Scanner(new File(("F:\\2.txt")));
while(scanner.hasNext()) {
while(scanner2.hasNext()) {
system.out.println(scanner.next() + "|" + scanner2.next() + "|");
}
//输出
first|second|third|first1|second1|third1|
fourth|fifth|sixth|fourth1|fifth1|sixth1|
答案 0 :(得分:0)
Scanner scanner = new Scanner(new File(("F:\\1.txt")));
Scanner scanner2 = new Scanner(new File(("F:\\2.txt")));
String[] line1, line2, res;
while (scanner.hasNext() && scanner2.hasNext()) {
line1 = scanner.next().split("\\|");
line2 = scanner2.next().split("\\|");
int len = Math.min(line1.length,line2.length);
res= new String[line1.length + line2.length];
for(int index = 0, counter = 0; index < len; index++){
res[counter++] = line1[index];
res[counter++] = line2[index];
}
if(line1.length > line2.length){
for(int jIndex = 2*line2.length, counter = 0;jIndex < (line1.length+line2.length);jIndex++ ){
res[jIndex] = line1[line2.length + (counter++)];
}
}else if(line2.length > line1.length){
for(int jIndex = 2*line1.length, counter = 0;jIndex < (line1.length+line2.length);jIndex++ ){
res[jIndex] = line2[line1.length + (counter++)];
}
}
String result = Arrays.asList(res).toString().replaceAll("(^\\[|\\]$)", "").replace(", ", "|");
System.out.println(result);
}
scanner.close();
scanner2.close();
如果两行包含相同数量的令牌,您可以放弃if条件
这将输出为,
first|first1|second|second1|third|third1
fourth|fourth1|fifth|fifth1|sixth|sixth1
和
String[] line1, line2, res;
while (scanner.hasNext() && scanner2.hasNext()) {
line1 = scanner.next().split("\\|");
line2 = scanner2.next().split("\\|");
res= new String[line1.length + line2.length];
int counter = 0;
res[counter++] = line1[0];
for(int index = 0; index < line2.length; index++){
res[counter++] = line2[index];
}
for(int index = 1; index < line1.length; index++){
res[counter++] = line1[index];
}
String result = Arrays.asList(res).toString().replaceAll("(^\\[|\\]$)", "").replace(", ", "|");
System.out.println(result);
}
scanner.close();
scanner2.close();
将输出
first|first1|second1|third1|second|third
fourth|fourth1|fifth1|sixth1|fifth|sixth