日期:2014-05-20  浏览次数:20939 次

急!请教个文件比较的问题?

有两个文本文件A和B,这两个文件里的内容类似(如AB两文件的数据大部分相同,只有少部分数据不同),要对这两个文件进
行比较,将这两个文件中的不同的数据找出来,然后存到一个新的文本文件里。

注:以A为基准进行比较;即,A里有的而B里没有的就将其不同的数据存到新文件;B里有的而A里没有的就不对其进行存储。

请教大侠们,要如何入手啊?

小弟现在的想法是两文件都存到字符串,然后在进步操作,不知道这样是否否可行啊?此外,还有没有更好的方法啊?

希望大虾们能提供下代码,最好是完整代码!

谢谢啦!!!!!很急的啊!!!!!


------解决方案--------------------
package test;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;

public class FileComper {
String sPath;
String sFilePath;
String sContent;
public static void main(String[] args) {
FileComper test = new FileComper();
String crlf = System.getProperty("line.separator");
String str1="你好这是测试字段xx"+crlf+"abcdefgaigeiieriepty";
String str2="你x这是测y字段yy"+crlf+"dbcdefgaigeiieriy";
test.writeFilebyExistsOver(str1, "d:\\1.txt");
test.writeFilebyExistsOver(str2, "d:\\2.txt");
test.readFile("d:\\1.txt", "d:\\2.txt");
}
public String readFile(String Filename,String Filename2) {
String FileName = Filename;
File myFile = new File(FileName);

File myFile2 = new File(Filename2);

if (!myFile.exists()) {
System.err.println("Can't Find " + FileName);
}
if (!myFile2.exists()) {
System.err.println("Can't Find " + Filename2);
}
StringBuffer temp = new StringBuffer();
String str3="";
try {
BufferedReader in = new BufferedReader(new FileReader(myFile));

BufferedReader in2 = new BufferedReader(new FileReader(myFile2));

String str="",str2="";

while ((str = in.readLine()) != null) {
str2 = in2.readLine();
System.out.println("a:"+str);
System.out.println("b:"+str2);
// System.out.println(f(str,str2));
str3 = str3+ f(str,str2); 

}
in.close();
in2.close();
writeFilebyExistsOver(str3, "d:\\3.txt");
} catch (IOException e) {
e.getStackTrace();
}
// System.out.print(temp.toString());
return temp.toString();
}

String f(String aStrA,String aStrB){
String str=""; //用来存储不同字符
for(int i=0;i<=aStrA.length();i++){
if(i==aStrA.length()){
break;
}
if(i>aStrB.length()-1){
str = str + aStrA.substring(i, aStrA.length());
break;
}else{
String a=aStrA.substring(i,i+1); //每次获取一个字符进行逐个比较
String b=aStrB.substring(i,i+1);
if(a.equals(b)||a==b){
continue;
}else{
str=str+a;
}
}

}

return str;
}

public void writeFilebyExistsOver(String datas, String Filename) {
FileOutputStream outSTr = null;
BufferedOutputStream Buff = null;
try {
File file = new File(Filename.toString());
if (file.exists()) {
delFile(Filename);
}
outSTr = new FileOutputStream(file);
Buff = new BufferedOutputStream(outSTr);
long begin0 = System.currentTimeMillis();
Buff.write(datas.getBytes());
Buff.flush();
Buff.close();
long end0 = System.currentTimeMillis();
System.out.println("BufferedOutputStream执行耗时:" + (end0 - begin0)
+ " 豪秒");
Buff.close();
outSTr.close();