首页 > 解决方案 > 从java中的文件中按id删除

问题描述

我的代码从文件中找到用户的 id 并将其放入数组中,但它不会从文件中删除该行。我想问题出在这个循环中(for(Object str:lines)),因为我的另一个类被称为“adh”,其中getter&setter和字符串functinos但是每当我将对象更改为str时它不会让我


public static void name_search() throws IOException, FileNotFoundException{
   Adherent adh = new Adherent();
   Scanner input= new Scanner(System.in);
   String id;
   System.out.println("Give ID: ");
   id = input.nextLine();
   File db = new File("adherent_db.txt");
   BufferedReader reader = new BufferedReader(new FileReader(db));
   String currentLine;
   boolean first = false;
   String[] fields = new String[0];
   List<String> lines = new ArrayList<String>();
   while((currentLine = reader.readLine()) !=null) {
       if(!first) {
           fields = currentLine.split(",");
           first = true;
       }
       else {// only if both of the user's inputs (name and surname) match a contact then i add this contact's info to an array
           String[] info=currentLine.split(",");
           if(info[0].equals(id)) {
               System.out.println("----There is a contact for the information you gave----");
               for (int i = 0; i < fields.length; i++ ) {
                   System.out.println(info[i]);                    
               }
               //contact_change(currentLine);
               lines.add(currentLine);
           }



       }
   }
   System.out.println("-------------------");
   reader.close();
   for(Object str:lines){//for every contatc that i found that is a match
       contact_delete(str.toString());
   } 

}           

public static void contact_delete(String line)  throws IOException, FileNotFoundException{
   File tempDB = new File("adherent_db_temp.txt");
   File db = new File("adherent_db.txt");


   BufferedReader reader1 = new BufferedReader(new FileReader(db));    
   String currentLine1;
   boolean first = false;
   String[] fields = new String[0];


       BufferedWriter writer = new BufferedWriter(new FileWriter(tempDB));
   while((currentLine1 = reader1.readLine()) !=null) {
       if(!first) {
           fields = currentLine1.split(",");
           writer.write(currentLine1 + "\n");
           first = true;
       }
       else if(!currentLine1.equals(line)){//if the current line in the reader is not the one we want to delete we write it to the temp file   
           writer.write(currentLine1 + "\n");
       }
   }
   reader1.close();
   writer.close();
   db.delete();//we delete the original file
   tempDB.renameTo(db);//we rename the temporary file to the original file's name
   System.out.println("Information was valid, deletion completed successfully");
}``` 

标签: javaarrays

解决方案


推荐阅读