user3322141
user3322141

Reputation: 158

How to write in existing file from list using Java by removing duplicate data?

I want to write in file that exists. My data is in the form of java list. Here is a sample of data :

snmp,192.168.20.1,cloud,
snmp,192.168.20.2,cloud,

I want to add line snmp,192.168.20.1,cloud123 in the file. It should update existing file content i.e.(snmp,192.168.20.1,cloud) by new contents given.

And if provided contents different from contents of file then append it to file?

Here is my workaround---

String tempFile = RunMTNew.instdir + "/var/";
File tempFileName = new File(tempFile+"hosts.tempFile");
try{
if(!tempFileName.exists()) {
tempFileName.createNewFile();
} 
}catch (FileNotFoundException e){
e.printStackTrace();
}
catch ( IOException ioe){
ioe.printStackTrace();
System.out.println("Exception occured while creating temp file");
}
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
PrintWriter tempoutfile= null;
 while((line = bufferedReader.readLine()) != null) {
     System.out.println("line before if "+ line);
     if(line!=null || (line = line.trim()) != "" ){
     System.out.println("line at start of while" + line);
     String[] lineFromFile = line.split(",");
 try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename, true)));
    ListIterator atwlist = arraytowrite.listIterator();
    String lineToWriteInFile = "";

while (atwlist.hasNext()) {
ArrayList atwlistline = (ArrayList) atwlist.next();
 System.out.println("array" + atwlistline);
 String lineToAdd = atwlistline.toString();
 lineToWriteIfNotFound = lineToAdd;
 System.out.println("After converting to string line is" + lineToAdd);
 System.out.println("lineFromFile contents are "+ lineFromFile[1]);
 if(lineToAdd.contains(lineFromFile[1])){
 lineToWriteInFile = lineToAdd;
 }
 else{
 lineToWriteInFile = line;
 }
}
 try{
 tempoutfile = new PrintWriter(new BufferedWriter(new FileWriter(tempFileName, true)));
 System.out.println("writing in file" +lineToWriteInFile);
tempoutfile.write(lineToWriteInFile);
tempoutfile.write("\n");
 }catch(IOException ioe){
     ioe.printStackTrace();
 System.out.println("Exception occured while writing in tempFile");
 }

tempoutfile.close();
} catch (IOException e) {
e.printStackTrace();
    System.out.println("Exception occured in outer try block");
}
 }//end of if
 }// end of while

 try{
 FileReader tempfileReader = new FileReader(tempFile+"hosts.tempFile");

 BufferedReader tempBufferedReader = new BufferedReader(tempfileReader);
 FileWriter fosFinal = new FileWriter(filename);
 PrintWriter outFinal = new PrintWriter(fosFinal);
 while((line = tempBufferedReader.readLine()) != null) {
     System.out.println("line from tempfile to write in main " + line);
    outFinal.write(line);
 }
 }catch(IOException ie){
     ie.printStackTrace();
     System.out.println("Exception occured while reading from temp and write into main file");
 }

Upvotes: 0

Views: 601

Answers (3)

Vishwas
Vishwas

Reputation: 7067

Use temp file to store temporarily contents of file.

Here is a code :

            ListIterator atwlist = arraytowrite.listIterator();
        while (atwlist.hasNext()) {
            ArrayList atwlistline = (ArrayList) atwlist.next();

            ListIterator atwlistlineL = atwlistline.listIterator();
            while (atwlistlineL.hasNext()) {

                firstWriter.write((String) atwlistlineL.next());
                firstWriter.write(",");
            }
            //firstWriter.write("\n");
            System.out.println(atwlistline);
        }
        firstWriter.close();

        //Write original file contents to another file i.e. tempFile2 
        try{
        FileReader fileReader = new FileReader(filename);
        BufferedReader bufferedReader = 
                new BufferedReader(fileReader);
        String line = "";
        while((line = bufferedReader.readLine()) != null) {
            secondWriter.write(line);
            secondWriter.write("\n");
        }
        secondWriter.close();
        bufferedReader.close();
        }catch(IOException ie){
            ie.printStackTrace();
            System.out.println("Exception occured while reading from main file");
        }
        //check and remove duplicate entries from file
        try{
        FileReader singleDeviceReader = new FileReader(file1Path);
        FileReader duplicateDeviceReader = new FileReader(file2Path);
        finalWriter = new PrintWriter(filename);

        BufferedReader bufferedReader1 = new BufferedReader(singleDeviceReader);
        BufferedReader bufferedReader2 = new BufferedReader(duplicateDeviceReader);
        String line1 = null;
        String line2 = null;
        boolean fileWriteFlag = false;
        String ifNotFind = "";
        while((line1 = bufferedReader1.readLine())!=null){
            String[] line1Split = line1.split(",");
            ifNotFind = line1;
            while((line2 = bufferedReader2.readLine())!=null){
                String[] line2Split = line2.split(","); 
                if (line2Split[1].equals(line1Split[1])){
                    finalWriter.write(line1);
                    finalWriter.write("\n");
                    fileWriteFlag = true;
                }
                else {
                    finalWriter.write(line2);
                    finalWriter.write("\n");

                }
            }
        }
        if(!fileWriteFlag){
            finalWriter.write(ifNotFind);
        }
        finalWriter.close();
        bufferedReader1.close();
        bufferedReader2.close();

        File t1 = new File (file1Path);
        File t2 = new File (file1Path);
        if (t1.exists()){
            t1.delete();
        }
        if (t2.exists()){
            t2.delete();
        }
        }catch (IOException ioe ){
            ioe.printStackTrace();
            System.out.println("Exception occured while reading both temp files");
        }

Upvotes: 1

Cyclops
Cyclops

Reputation: 689

First get all the existing data set to a list. now iterate your new list(which need to append) using a for loop and get a inner loop and check condition and add/skip.

Pseudo code:

List my_existing_list;
List my_new_list;

foreach(my_new_list){

     foreach(my_existing_list){

        if(equal to an existing item){

          //skip

        }else{

           //append to file
         }

     }

}

Upvotes: 0

hanumant
hanumant

Reputation: 1101

Instead of checking and comparing the content from the file I suggest you create list with unique items. Which will save your time to parse the file content and update operations on file and your code as well

Upvotes: 0

Related Questions