java分别读取两个txt文件里的数据再进行比较。再分别列出这两个文件中共...
发布网友
发布时间:2024-10-16 14:16
我来回答
共1个回答
热心网友
时间:2024-10-16 14:44
ID后面是以个推文还是多个推文?
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class FileCompare {
public static void main(String[] args) throws IOException {
FileCompare c = new FileCompare();
c.compareFile();
}
public void compareFile(){
File file = new File("D:\\1.txt");
File file2 = new File("D:\\2.txt");
Set fileTextSet = new HashSet();
Set file2TextSet = new HashSet();
try {
getText(file,fileTextSet);
getText(file2,file2TextSet);
compareSet(fileTextSet, file2TextSet);
} catch (Exception e) {
e.printStackTrace();
}
}
private void compareSet(Set textSet,Set StextSet2){
for (Iterator iterator = textSet.iterator(); iterator.hasNext();) {
String name = (String) iterator.next();
if(StextSet2.contains(name)){
System.out.println("共同报文:"+name);
}else{
System.out.println("1独有报文:"+name);
}
}
for (Iterator iterator = StextSet2.iterator(); iterator.hasNext();) {
String name = (String) iterator.next();
if(!textSet.contains(name)){
System.out.println("2独有报文:"+name);
}
}
}
private void getText(File file,Set textSet) throws IOException {
BufferedReader br = null;
InputStream is = null;
try {
is = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String lineStr = null;
while ((lineStr = br.readLine())!=null) {
String text = lineStr.substring(lineStr.indexOf(":"));//按照需求切分
textSet.add(text);
}
if(br!=null){
br.close();
}
if(is!=null){
is.close();
}
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
} finally {
if(br!=null){
br.close();
}
if(is!=null){
is.close();
}
}
}
}