How to delete an entry from a random access file?

I was wondering how I can delete an entry from my random access file.

Here's how I add to my RAF, but not sure how to remove it: X

public void addNewStudent(String name, String formClass, String emailAddress, String country1, String country2, String universityChoice) { try { RandomAccessFile theFile = new RandomAccessFile("studentData.dat","rw"); long records = (theFile.length()+299)/300; //Number of records if(theFile.length()>0) //Check if the file is empty or not { for(long x=0;x<records;x++) { theFile.seek(x*300); String currentName = theFile.readUTF(); if(name.equalsIgnoreCase(currentName)) //Check if student exists in database { output("This student exist already"); //Output this if exists } else // or else write a new record { theFile.seek(records*300); theFile.writeUTF(name); //Write student name theFile.seek((records*300)+50); theFile.writeUTF(formClass); //Writes students' form class theFile.seek((records*300)+60); theFile.writeUTF(emailAddress); //Writes students' email theFile.seek((records*300)+100); theFile.writeUTF(country1); //Writes students' country choice #1 theFile.seek((records*300)+140); theFile.writeUTF(country2); //Writes students' country choice #2 theFile.seek((records*300)+180); theFile.writeUTF(universityChoice); //Writes students' university choices students.add(name,formClass,emailAddress,country1,country2,universityChoice); } } } else //If the file isn't empty, then just write { theFile.seek(records*300); theFile.writeUTF(name); //Write student name theFile.seek((records*300)+50); theFile.writeUTF(formClass); //Writes students' form class theFile.seek((records*300)+60); theFile.writeUTF(emailAddress); //Writes students' email theFile.seek((records*300)+100); theFile.writeUTF(country1); //Writes students' country choice #1 theFile.seek((records*300)+140); theFile.writeUTF(country2); //Writes students' country choice #2 theFile.seek((records*300)+180); theFile.writeUTF(universityChoice); //Writes students' university choices students.add(name,formClass,emailAddress,country1,country2,universityChoice); } } catch(IOException e) { output("Error while adding new student"); } } 
0
source share
2 answers

I would have a remote flag, and if it is set, do not read it.

+2
source

Best way: create a delete dialog method. Ask this method to write an empty record to a file. Creating an empty record is easy if your constructor is configured correctly.

When an empty record is written as a series of zeros and zeros, and if your program is configured to only display records with corresponding values, it will not display records with zero values.

0
source

Source: https://habr.com/ru/post/1244878/


All Articles