我有两个不同的大文本文件z和xz,每个大小为MB。将z文本文件内容与xz文本文件内容进行比较(如果有任何内容匹配)将其写入新的文本文件输出。
验证需要花费大量时间,而且不会写入输出文件。
如何写入输出文件?
public class CompareTwo {
static int count1 = 0;
static int count2 = 0;
static String arrayLines1[] = new String[countLines("C:/Users/THAKUR SANTHOSHI/Desktop/z.txt")];
static String arrayLines2[] = new String[countLines("C:/Users/THAKUR SANTHOSHI/Desktop/xz.txt")];
public static void main(String args[]) {
findDifference("C:/Users/THAKUR SANTHOSHI/Desktop/z.txt", "C:/Users/THAKUR SANTHOSHI/Desktop/xz.txt");
try {
displayRecords();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static int countLines(String File) {
int lineCount = 0;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(File));
while ((br.readLine()) != null) {
lineCount++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return lineCount;
}
public static void findDifference(String File1, String File2) {
String contents1 = null;
String contents2 = null;
BufferedReader buf1 = null;
BufferedReader buf2 = null;
try {
FileReader file1 = new FileReader(File1);
FileReader file2 = new FileReader(File2);
buf1 = new BufferedReader(file1);
buf2 = new BufferedReader(file2);
while ((contents1 = buf1.readLine()) != null) {
arrayLines1[count1] = contents1;
count1++;
}
while ((contents2 = buf2.readLine()) != null) {
arrayLines2[count2] = contents2;
count2++;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (buf1 != null) {
try {
buf1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (buf2 != null) {
try {
buf2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void displayRecords() throws IOException {
// true = append file
File file = new File("D:/out.txt");
FileWriter fileWritter = new FileWriter(file.getName(), true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
for (int i = 0; i < arrayLines1.length; i++) {
String a = arrayLines1[i];
for (int j = 0; j < arrayLines2.length; j++) {
String b = arrayLines2[j];
boolean result = a.equals(b);
if (result == true) {
if (a != null && !a.trim().isEmpty()) {
bufferWritter.write(a);
bufferWritter.flush();
System.out.println(a + " Copied.");
}
}
}
}
bufferWritter.close();
}
}