Read and Write in the same file simultaneously in Java

java string file bufferedreader bufferedwriter

431 观看

1回复

1 作者的声誉

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

作者: QuesTime 的来源 发布者: 2017 年 12 月 27 日

回应 1


0

139 作者的声誉

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

作者: zealvault 发布者: 2018 年 1 月 4 日
32x32