RandomAccessFile类(java高级02_02)
1) 该类支持随机访问功能
package IO;
import java.io.*;
public class RandomFileTest {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
Employee e1=new Employee("zhangsan",258);//定义一个对象
Employee e2=new Employee("李四",24);
Employee e3=new Employee("wangwu",25);
//byte[] buf=new byte[Employee.LEN];
String name="";//定义一个全局的字符串,存名字
//int len=0;
RandomAccessFile ra;
ra = new RandomAccessFile("employee.txt","rw");//建立文件读写器,能读能写
ra.writeChars(e1.getName());
ra.writeInt(e1.getAge());
ra.writeChars(e2.getName());
ra.writeInt(e2.getAge());
ra.writeChars(e3.getName());
ra.writeInt(e3.getAge());
ra.close();
RandomAccessFile raf=new RandomAccessFile("employee.txt","r");//建立文件读写器,只可读
raf.skipBytes(Employee.LEN*2+4);//把读标移动到第二个对象处,存储的是unicode编码,每个占2个字符
//len=raf.read(buf);
//name=new String(buf,0,len);
for (int i = 0; i < Employee.LEN; i++) {
name+=raf.readChar();//逐个读取字符,累加成字符串
}
System.out.println(name.trim()+":"+raf.readInt());//显示对象信息
name="";//清空字符串
raf.seek(0);//光标移动到第一个对象处
//len=raf.read(buf);
//name=new String(buf,0,len);
for (int i = 0; i < Employee.LEN; i++) {
name+=raf.readChar();
}
System.out.println(name.trim()+":"+raf.readInt());
name="";
raf.skipBytes(Employee.LEN*2+4);//读完第一个对象,把光标移动到下一对象
//len=raf.read(buf);
//name=new String(buf,0,len);
for (int i = 0; i < Employee.LEN; i++) {
name+=raf.readChar();
}
System.out.println(name.trim()+":"+raf.readInt());
}
}
最终执行结果:
李四:24
zhangsan:258
wangwu:25