比较两个文本文档在 java 中的相似性
comparing two text document for similarities in java
我编写了用于比较两个文本文件的代码。只有当匹配项与第一个文本文件中的位置相同时,它才会显示结果。我想在其他文本文件的任何地方找到匹配项。请建议一种方法来做到这一点。我写的代码如下所示:
import java.io.*;
public class CompareTextFiles {
public static void main(String args[]) throws Exception {
FileInputStream fstream1 = new FileInputStream("text1.txt");
FileInputStream fstream2 = new FileInputStream("text2.txt");
DataInputStream in1= new DataInputStream(fstream1);
DataInputStream in2= new DataInputStream(fstream2);
BufferedReader br1 = new BufferedReader(new InputStreamReader(in1));
BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
String strLine1, strLine2;
while((strLine1 = br1.readLine()) != null && (strLine2 = br2.readLine()) != null){
if(strLine1.equals(strLine2)){
System.out.println(strLine1);
}
}
}
}
将其中一个文件的全部内容存储到一个字符串中,而不是逐行比较。
<code>String strLine1, strLine2;
StringBuffer strFile2 = new StringBuffer();
//Store the contents of File2 in strFile2
while((strLine2 = br2.readLine()) != null) {
strFile2.append(strLine2);
}
//Check whether each line of File1 is in File2
while((strLine1 = br1.readLine()) != null){
if(strFile2.toString().contains(strLine1)){
System.out.println(strLine1);
}
}
我编写了用于比较两个文本文件的代码。只有当匹配项与第一个文本文件中的位置相同时,它才会显示结果。我想在其他文本文件的任何地方找到匹配项。请建议一种方法来做到这一点。我写的代码如下所示:
import java.io.*;
public class CompareTextFiles {
public static void main(String args[]) throws Exception {
FileInputStream fstream1 = new FileInputStream("text1.txt");
FileInputStream fstream2 = new FileInputStream("text2.txt");
DataInputStream in1= new DataInputStream(fstream1);
DataInputStream in2= new DataInputStream(fstream2);
BufferedReader br1 = new BufferedReader(new InputStreamReader(in1));
BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
String strLine1, strLine2;
while((strLine1 = br1.readLine()) != null && (strLine2 = br2.readLine()) != null){
if(strLine1.equals(strLine2)){
System.out.println(strLine1);
}
}
}
}
将其中一个文件的全部内容存储到一个字符串中,而不是逐行比较。
<code>String strLine1, strLine2;
StringBuffer strFile2 = new StringBuffer();
//Store the contents of File2 in strFile2
while((strLine2 = br2.readLine()) != null) {
strFile2.append(strLine2);
}
//Check whether each line of File1 is in File2
while((strLine1 = br1.readLine()) != null){
if(strFile2.toString().contains(strLine1)){
System.out.println(strLine1);
}
}