原测试文件1:0.txt
内容:
1111
2222
3333
4444
新测试文件2:1.txt
内容:
1111
xxxx
yyyy
2222
4444
需要在控制台输出:
在第2行上方新增:xxxx,yyyy
第3行被删除
ps:如果一个行内容被更改,看做是删除后新增
public static void main(String[] args) {
//创建存储文件内容的列表
ArrayList oldList = new ArrayList();
ArrayList newList = new ArrayList();
//文件地址
String oldPath = "C:\\Users\\Administrator\\Desktop\\0.txt";
String newPath = "C:\\Users\\Administrator\\Desktop\\1.txt";
//读取文件
File file0 = new File(oldPath);
File file1 = new File(newPath);
try {
//提出0.txt文件内容
InputStream oldInputStream = new FileInputStream(file0);
InputStreamReader oldInputStreamReader = new InputStreamReader(oldInputStream);
BufferedReader oldReader = new BufferedReader(oldInputStreamReader);
//提出1.txt文件内容
InputStream newInputStream = new FileInputStream(file1);
InputStreamReader newInputStreamReader = new InputStreamReader(newInputStream);
BufferedReader newReader = new BufferedReader(newInputStreamReader);
String oldStr = "";
String newStr = "";
while ((oldStr = oldReader.readLine()) != null) {
oldList.add(oldStr);
}
while ((newStr = newReader.readLine()) != null) {
newList.add(newStr);
}
System.out.println("0.txt:");
oldList.forEach(System.out::println);
System.out.println("1.txt:");
newList.forEach(System.out::println);
System.out.println("==================result==================");
//删除
for (int i = 0; i < oldList.size(); i++) {
int delete = 0;
for (int j = 0; j < newList.size(); j++) {
if (oldList.get(i).equals(newList.get(j))) {
delete++;
}
}
if (delete == 0) {
System.out.println("第" + (i + 1) + "行被删除");
}
}
//添加
List insert = new ArrayList<String>();
for (int i = 0; i < newList.size(); i++) {
if(oldList.indexOf(newList.get(i))<0){
insert.add(newList.get(i));
}else {
if(!insert.isEmpty()){
System.out.println("第"+(oldList.indexOf(newList.get(i))+1)+"行前新添:");
insert.forEach(System.out::println);
insert.clear();
}
}
}
if(!insert.isEmpty()){
System.out.println("文件最后新添:");
insert.forEach(System.out::println);
}
System.out.println("===================end====================");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
一共有三种情况,增加,删除,更改。更改被看做是删除加添加,那么实际只有两种情况:增加,删除
删除的话拿原版本中的数据去新版本遍历对比,或者用isEmpty()判断是否存在,不存在就确认删除,控制台输出
添加用新版本去原版本对比,判断是否是新增,是的话标记(添加到集合中),当碰到在原版本存在的行时,说明在此行前新增集合内的值,打印后清空集合,之后继续判断,判断到最后,如果集合内还有值,说明是添加到文件最后的。