📄 appendfile.java
字号:
//【例9.9】 在文件中添加不重复数据。
import java.io.*;
public class AppendFile
{
private RandomAccessFile rafile;
public AppendFile(String filename) throws IOException
{
File file = new File(filename);
if (file.exists()) //如果指定文件已存在,则删除
file.delete();
this.rafile = new RandomAccessFile(filename,"rw"); //创建文件对象,可读写
}
public boolean search(int k) throws IOException //在文件中查找指定值
{
this.rafile.seek(0); //设置文件读指针在文件开始处的第1个整数位置
while (true) //文件未结束时
try
{
if (this.rafile.readInt()==k) //读取一个整数,文件读指针自动向后移动
return true; //查找成功
}
catch (EOFException ioe) //捕获到达文件尾异常
{
return false; //只有到文件结束时,才能确定查找不成功
}
}
public void append(int[] table) throws IOException //在文件中添加数据,不重复添加相同数据
{
for (int i=0;i<table.length;i++)
{
boolean find=this.search(table[i]);
System.out.println(table[i]+" "+find);
if (!find) //在文件中未找到
{
this.rafile.writeInt(table[i]); //向文件尾写入一个整数,文件写指针自动向后移动
}
}
System.out.println();
}
public void readFromFile() throws IOException //从指定文件中读取整数
{
System.out.println("readFromFile ");
this.rafile.seek(0);
while (true) //文件未结束时
try
{
System.out.print(this.rafile.readInt()+" ");
}
catch (EOFException ioe)
{
System.out.println();
this.rafile.close(); //关闭文件
break;
}
}
public static void main(String args[]) throws IOException
{
int[] table={15,32,11,32,15,56,11,78};
AppendFile afile = new AppendFile("Random.int");
afile.append(table);
afile.readFromFile();
}
}
/*
程序运行结果如下:
15 false
32 false
11 false
32 true
15 true
56 false
11 true
78 false
readFromFile
15 32 11 56 78
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -