Organizational Research By

Surprising Reserch Topic

Experts Most Trusted Topic

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 :

I want to add line snmp,,cloud123 in the file. It should update existing file content i.e.(snmp,,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");
if(!tempFileName.exists()) {
}catch (FileNotFoundException e){
catch ( IOException ioe){
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);
 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]);
 lineToWriteInFile = lineToAdd;
 lineToWriteInFile = line;
 tempoutfile = new PrintWriter(new BufferedWriter(new FileWriter(tempFileName, true)));
 System.out.println("writing in file" +lineToWriteInFile);
 }catch(IOException ioe){
 System.out.println("Exception occured while writing in tempFile");

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

 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);
 }catch(IOException ie){
     System.out.println("Exception occured while reading from temp and write into main file");

asked Jun 18, 2015 in Core java by rajesh
0 votes

Related Hot Questions

Government Jobs Opening