简体   繁体   中英

I can't read and then write the data in the same text file

In this code i am searching for a string in a file named source and if it doesn't exist i have to write the string in the same file(source). When I run this code the whole program doesn't respond. When I don't read from the file and directly write the program works. What am i doing wrong?

if(addChoice.getSelectedItem().equals("Source")){ 
    int i=0;
    try {
        FileInputStream fis=new FileInputStream("source.txt");
        BufferedReader fd=new BufferedReader(new InputStreamReader(fis));
        String source=fd.readLine();
        while(source!=null){
            if(source.equals(addTextField.getText())){
                i++;break;
            }
        }
        fis.close();
        fd.close();
    } catch (Exception e5) {
    }  
    if(i==0){
        try {
            FileOutpuStream fis=new FileOutputStream("source.txt",true);
            BufferedWriter fd=new BufferedWriter(new OutputStreamWriter(fis));
            fd.newLine();
            fd.write(addTextField.getText());
            fis.flush();
            fd.flush();
            fis.close();
            fd.close();                   
        } catch (Exception e1) {                           
        }                      
    }
    else{
        addLabel.setText("Already Exists");
    }
    addLabel.setVisible(true);
}
String source=fd.readLine();
while(source!=null){
  if(source.equals(addTextField.getText())){
    i++;break;
  }
}

If source is not null and source.equals(addTextField.getText()) is false , you loop forever.

Do the readline() in the loop.

String source = null;
while((source = fd.readLine()) != null){
  if(source.equals(addTextField.getText())){
    i++;
    break;
  }
}

Besides, you should avoid choking your exceptions :

catch (Exception e1) {                           
} 

Print them or better log them :

catch (Exception e1) {                           
    e1.printStackTrace();
} 

catch (Exception e1) {                           
    LOGGER.error("Error during reading writing operation", e1);
} 

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