62,614
社区成员
发帖
与我相关
我的任务
分享
public static void main(String[] args) throws Exception{
TestIndexOf in=new TestIndexOf(); //这个类里有我自己写的indexof方法,下文中你可以自己改成java自带的indexof方法
Charset c=Charset.forName("GBK"); //设置编码格式
List<String> list= Files.readAllLines(Paths.get("d:/qqq/a.txt"),c); //读取a文件数据
List<String> list2= Files.readAllLines(Paths.get("d:/qqq/b.txt"),c);//读取b文件数据
List<String> list3=new ArrayList<>();
int n=0,m=0;
while(n<list.size()&&m<list2.size()){
int head1=Integer.valueOf(list.get(n).substring(0, in.myIndexof(" ", list.get(n)))); //截取文件每一行开头数字,注意myindexof是我自己写的indexof方法,你可以将in.myIndexof(" ", list.get(n))
int head2=Integer.valueOf(list2.get(m).substring(0, in.myIndexof(" ", list2.get(m)))); //改成 list.get(n).indexOf(" ")即可,后面也是一样
if(head1==head2){ //比较两行开头数字大小,相等则将b文件的当前行数据内容去掉开头数字再拼接上a文件的当前行数内容
list3.add(list.get(n)+list2.get(m).substring(in.myIndexof(" ", list2.get(m))));
n++; //n,m都加一向后继续索引
m++;
}else if(head1>head2){
list3.add(list2.get(m));
m++;
}else{
list3.add(list.get(n));
n++;
}
if(n==list.size()&&m!=list2.size()){
for (int i = m; i <list2.size() ; i++) {
list3.add(list2.get(i));
}
}else if(m==list2.size()&&n!=list.size()){
for (int j = n; j <list.size() ; j++) {
list3.add(list.get(j));
}
}
}
list3.forEach(System.out::println);
if(!Files.exists(Paths.get("d:/qqq/c.txt"))){
Files.createFile(Paths.get("d:/qqq/c.txt"));
}
Files.write(Paths.get("d:/qqq/c.txt"), list3);
}
可能写的有点臭,还是发出来吧,注释也懒得写了,应该也不难理解
public static void main(String[] args) {
String pathA = "D:/a.txt"; //a.txt的文件路径
String pathB = "D:/b.txt"; //b.txt的文件路径
String pathC = "D:/c.txt"; //c.txt的文件路径
File fileA = new File(pathA);
File fileB = new File(pathB);
File fileC = new File(pathC);
try {
if (!fileC.exists()){
fileC.createNewFile();
}
BufferedReader brA = new BufferedReader(new FileReader(fileA));
BufferedReader brB = new BufferedReader(new FileReader(fileB));
BufferedWriter bwC = new BufferedWriter(new FileWriter(fileC));
String strA = null, strB = brB.readLine();
while ((strA = brA.readLine()) != null){
if (strB != null){
int indexA = Integer.parseInt(strA.substring(0, strA.indexOf(" ")));
int indexB = Integer.parseInt(strB.substring(0, strB.indexOf(" ")));
if (indexA < indexB){
bwC.write(strA + "\r\n");
}
if (indexA == indexB){
bwC.write(strA + strB.substring(strB.indexOf(" ") - 1, strB.length() - 1) + "\r\n");
strB = brB.readLine();
}
if (indexA > indexB){
bwC.write(strB + "\r\n");
strB = brB.readLine();
}
} else {
bwC.write(strA + "\r\n");
}
}
bwC.flush();
bwC.close();
brB.close();
brA.close();
} catch (IOException e) {
e.printStackTrace();
}
}