简体   繁体   English

在Java中同时读取和写入同一文件

[英]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 我想要的是在文件B中的文件A中写一个“字符串”,如果它不存在于文件B中,则知道B开头是空的

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 问题是,如果文件A中有重复的字符串

Following JB Nizet's answer, here some pseudo code 遵循JB Nizet的回答,这里有一些伪代码

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 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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