Java 如何从随机访问文件中删除记录?
我想知道如何从随机访问文件中删除记录 下面是我如何添加到我的RAF,但不知道如何删除它:XJava 如何从随机访问文件中删除记录?,java,random-access,Java,Random Access,我想知道如何从随机访问文件中删除记录 下面是我如何添加到我的RAF,但不知道如何删除它:X public void addNewStudent(String name, String formClass, String emailAddress, String country1, String country2, String universityChoice) { try { RandomAccessFile theFile = new RandomAccess
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");
}
}
public void addNewStudent(字符串名称、字符串formClass、字符串emailAddress、字符串country1、字符串country2、字符串universityChoice)
{
尝试
{
RandomAccessFile theFile=新的RandomAccessFile(“studentData.dat”、“rw”);
长记录=(theFile.length()+299)/300;//记录数
if(theFile.length()>0)//检查文件是否为空
{
对于(长x=0;x我会有一个删除标志,如果设置了,就不要读入它。最佳方法:创建一个删除对话框方法。让该方法将一个空白记录写入文件。如果构造函数设置正确,则创建空白记录很容易
当空白记录被写为一系列零点和零值时,如果你的程序被设置为只显示正确值的记录,它将不会显示任何0个/空值的记录。
为什么不使用数据库?如果你需要你的数据在一个可移植的文件中,你可以使用它。这是一个学校项目,所以我必须在标准之内:(您是否希望删除此问题?能否解释您最近的编辑?将第一个字段设置为“非法”值,如“[[deleted]]”,该值不太可能是任何人的姓名。或者甚至添加一个名为deleted
的布尔标志,并将其设置为true或false。查找位置并将所有内容向上移动会有多困难?