我必须输入文本文件,并且要在修改第二个文件的内容的位置打印行号?
file 1:
1/ hi
2/
3/
4/ start
5/ {
6/
7/ while(){
8/ }
9/ }
file 2:
1/ hi
2/
3/
4/
5/ start
6/
7/
8/ {
9/ if(
10/ while(){
11/ }
12/ }.
输出应为:9(如果在文件2中添加了额外内容)。请注意,可能会有不必要的标签和换行符。有人可以帮助我解决此问题吗?
import java.util.Scanner;
//convert a file into a file_simple form
File simplified(String src , String srcPath , String name) throws FileNotFoundException{
File fileSrc = new File(src);
File fileDest = new File(srcPath + "\\" + name + "_simple");
Scanner scSrc = new Scanner(fileSrc);
PrintWriter pw = new PrintWriter(fileDest);
while(scSrc.hasNextLine()) {
String take = scSrc.nextLine();
if(take.equals("")) {
continue;
}
String take1 = take.trim();
pw.println(take1);
}
pw.close();
scSrc.close();
return fileDest;
}
//write what difference the second file has
void differenceInTwoFiles(File file1 , File file2 , String logPath , String UserName) throws FileNotFoundException {
File file1Simple = simplified(file1.getAbsolutePath() , file1.getParentFile().getAbsolutePath() , file1.getName());
File file2Simple = simplified(file2.getAbsolutePath() , file2.getParentFile().getAbsolutePath() , file2.getName());
System.out.println(file2.getAbsolutePath() +" " + file2.getParentFile().getAbsolutePath() +" "+ file2.getName());
File log = new File(logPath);
PrintWriter pwLog = new PrintWriter(log);
Scanner scF1 = new Scanner(file1Simple);
Scanner scF2 = new Scanner(file2Simple);
while(scF1.hasNextLine() && scF2.hasNextLine()) {
String first = scF1.nextLine();
String second = scF2.nextLine();
if(!first.equals(second)) {
pwLog.println(UserName + " has MODIFIED in " + file2.getName() + " : " + second);
}
}
pwLog.close();
scF1.close();
scF2.close();
}
}
答案 0 :(得分:0)
我赞成使用Java处理此任务,而不赞成使用 ,因为那里已经有非常好的工具可以按照您的意愿进行操作。例如,Linux有一个diff
工具,可以在这里很好地工作:
diff file1.txt file2.txt
至少,diff
的输出会标记出两个文件之间不一致的每一行,也许这足以满足您的要求。