Java 我能';t在同一文本文件中读取然后写入数据

Java 我能';t在同一文本文件中读取然后写入数据,java,Java,在这段代码中,我在名为source的文件中搜索一个字符串,如果它不存在,我必须在同一个文件(source)中写入该字符串。当我运行这段代码时,整个程序没有响应。当我不从文件中读取而直接编写程序时。我做错了什么 if(addChoice.getSelectedItem().equals("Source")){ int i=0; try { FileInputStream fis=new FileInputStream("source.txt");

在这段代码中,我在名为source的文件中搜索一个字符串,如果它不存在,我必须在同一个文件(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);
}
如果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);
} 
如果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);
} 

catch(异常e1){}
-首先打印出异常消息和堆栈跟踪。如果您得到一个,但不知道如何利用它,请将stacktrace添加到您的问题中(编辑它)。这是一个“不要”的问题。费尔多因为我是一个新手,我不知道我们不应该通过GUI应用程序读写。这就是为什么我写了一篇评论:)现在我要杀了我的教授,告诉他为什么我们不应该用GUI做IO。他应该通知我的。现在要么他活着要么我xD…
catch(Exception e1){}
-首先打印出异常消息和堆栈跟踪。如果您得到一个,但不知道如何利用它,请将stacktrace添加到您的问题中(编辑它)。这是一个“不要”的问题。费尔多因为我是一个新手,我不知道我们不应该通过GUI应用程序读写。这就是为什么我写了一篇评论:)现在我要杀了我的教授,告诉他为什么我们不应该用GUI做IO。他应该通知我的。如果我的回答解决了你的问题,请毫不犹豫地接受我的回答。如果我的回答解决了你的问题,请毫不犹豫地接受我的回答。