繁体   English   中英

我无法在同一文本文件中读取然后写入数据

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

在这段代码中,我正在名称为source的文件中搜索字符串,如果不存在,则必须在同一文件(源)中写入字符串。 当我运行这段代码时,整个程序没有响应。 当我不从文件中读取并直接编写程序时,它可以工作。 我究竟做错了什么?

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;
  }
}

如果source不为null并且source.equals(addTextField.getText())false ,则永远循环。

在循环中执行readline()

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

此外,您应该避免阻塞异常:

catch (Exception e1) {                           
} 

打印它们或更好地记录它们:

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

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

暂无
暂无

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

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