简体   繁体   中英

Read and Write in the same file simultaneously in Java

What i want is to write a "string" that is in file A in file B if it does not already exist in file B, knowing that B is empty at the beginning

BufferedReader bfA=new BufferedReader(new FileReader("A.txt"));
        BufferedReader bfB=new BufferedReader(new FileReader("B.txt"));
        BufferedWriter writerB=new BufferedWriter(new FileWriter("B.txt"));
        String line1,line2;
        boolean bool=false;
        while((line1=bfA.readLine())!=null){
            bfB=new BufferedReader(new FileReader("B.txt"));
            while((line2=bfB.readLine())!=null){

                if(line1.equals(line2)){
                    bool=true;}}

        if(bool==false){
            writerB.write(line1);
        }
        }

the problem is that if in the File A there's duplicate string

Following JB Nizet's answer, here some pseudo code

readerA, writerB = "", memory = ""
while(readerA.hasNextLine()){
       line = readerA.nextLine()
  if(line isNotPresent in memory){
       add line to memory 
       add line in writerB
   }
}

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM