import java.io.*;
public class randomAccess {
/**
* @param args
*/
String Filename;
public randomAccess(String Filename)
{this.Filename=Filename;}
public void writeEmployee(Employee e,int n)throws Exception
{
RandomAccessFile ra=new RandomAccessFile(Filename,"rw");
ra.seek(n*20);
for(int i=0;i<8;i++)
ra.writeChar(e.name[i]);
ra.writeInt(e.age);
ra.close();
}
public void readEmployee(int n)throws Exception
{
char[] buf=new char[8];
RandomAccessFile ra=new RandomAccessFile(Filename,"r");
ra.seek(n*20);
for(int i=0;i<8;i++)
buf[i]=ra.readChar();
System.out.print("name: ");
System.out.println(buf);
System.out.println("age: "+ra.readInt());
ra.close();
}
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
File f=new File(args[0]);
if(f.exists())
{f.delete();
f.createNewFile();
}
else
f.createNewFile();
randomAccess r=new randomAccess(args[0]);
r.writeEmployee(new Employee("fhgujghdf",30), 0);
r.writeEmployee(new Employee("yjngilmsme",23), 1);
r.writeEmployee(new Employee("rf",12), 2);
r.writeEmployee(new Employee("4grw",30), 3);
for(int i=0;i<4;i++)
r.readEmployee(i);
}
}
class Employee
{
char name[]={'/u0000','/u0000','/u0000','/u0000','/u0000','/u0000','/u0000','/u0000'};
int age;
public Employee(String name,int age)throws Exception
{
if(name.toCharArray().length>8)
System.arraycopy(name.toCharArray(), 0, this.name, 0, 8);
else
System.arraycopy(name.toCharArray(), 0, this.name, 0, name.toCharArray().length);
this.age=age;
}
}
/*学习心得
1.RandomAccessFile类
RandomAccessFile(String filename,String mode) 创建从中读取和向其中写入(可选)的随机存取文件流,该文件具有指定名称。
void seek(long pos) 设置到此文件开头测量到的文件指针偏移量,在该位置发生下一个读取或写入操作。
void wirtechar(int v) 按双字节值将 char 写入该文件,先写高字节
void readchar() 从此文件读取一个 Unicode 字符
2.String类
char[] toCharArray() 以字符数组形式返回字符串
3.System.arraycopy(char[] s,long spos,char[] d,long dpos,long length) 用作字符数组之间的复制
*/