Compare Text in 2 files and write the difference in a new file

Here I am reading 2 files, first file data is added to list.second file data is added to another list.Then converting 2 list to 2 Hashset. Then i am removing 1st hashset from the 2nd one.In this process all the common string will get removed and the new Hashset will have the difference data.
/**
 * Getting 2 text files with single column data in each, need to find out the difference and write the difference between the 2 files to a new file.
 */
public class CompareTwoFiles {
public static List readcsv(String filename) {
List l=new ArrayList();
String tempstr = "";
String dataStr = "";
int rownum = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
try {
String line = "";
while ((line = br.readLine()) != null) {
l.add(line);
// System.out.println(dataStr);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return l;
}

   public CompareTwoFiles() {
       // TODO Auto-generated constructor stub
   }

   public static void writecsv(String str,String filename){
FileWriter fileWriter = null;
       try {
fileWriter = new FileWriter("E://"+filename+"_DIFF.txt");
           fileWriter.append(str);
           System.out.println("DONE");
       } catch (Exception e) {
System.out.println("Error in CsvFileWriter !!!");
e.printStackTrace();
} finally {

try {
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
System.out.println("Error while flushing/closing fileWriter !!!");
               e.printStackTrace();
}

}

}
   public static void main(String[] args) {

   List ls1 = readcsv("E://TEMPLATE.txt");
   List ls2 = readcsv("E://SETSHEET.txt");
   Set set1 = new HashSet();
   set1.addAll(ls1);
   Set set2 = new HashSet();
   set2.addAll(ls2);
   set2.removeAll(set1);
   String str="";
   for (String diffElement : set2) {
    str=str+diffElement.toString()+"\n";
    System.out.println(diffElement.toString());
   }
   writecsv(str,"SETSHEET");
   }
}

Comments

Popular posts from this blog

Spring MVC- Redirect from one controller to another

Integrating Struts2 with Spring Security using Custom Login Form