import java.io.*; 
public class RAFDemo
{ 
	public static void main(String args[]) 
	{ 
		File f=new File("student.dat"); 
		try 
		{ 
			// 新建一个可读写RandomAccessFile
			RandomAccessFile raf=new RandomAccessFile(f,"rw"); 
			// 新添一条记录
			Student zhang =new Student("zhangtao",18); 
			zhang.writeData(raf); 
			// 再加一条
			Student li=new Student("liqiang",16); 
			li.writeData(raf); 
			// 再加一条
			Student wang=new Student("wanglong",17); 
			wang.writeData(raf); 
			// 返回
			raf.seek(0); 
			// 输出
			for(long i=0;i<raf.length();i=raf.getFilePointer()) 
			{ 
				Student temp=new Student(); 
				String name=temp.readName(raf); 
				int age=temp.readAge(raf); 
				System.out.println("the name is "+name); 
				System.out.println("the age is "+String.valueOf(age)); 
			} 
		} 
		catch(Exception e) 
		{ 
			System.out.println("have a error"); 
		} 
	} 
} 

class Student 
{ 
	int nameSize=30; 
	String name; 
	int age; 

	Student() 
	{ 
	} 

	Student(String name,int age) 
	{ 
		this.name=name; 
		this.age=age; 
	} 

	public void writeData(RandomAccessFile raf)throws Exception 
	{ 
		for(int i=0;i<nameSize;i++) 
		{ 
			char str=0; 
			if(i<name.length()) 
			{ 
				str=name.charAt(i); 
			} 
			raf.writeChar(str); 
		} 
		raf.writeInt(age); 
	} 

	public String readName(RandomAccessFile raf)throws Exception 
	{ 
		StringBuffer temp=new StringBuffer(nameSize); 
		int i=0; 
		boolean more=true; 
		while(more&&i<nameSize) 
		{ 
			char str=raf.readChar(); 
			i++; 
			if(str==0) 
			{ 
				more=false; 
			} 
			else 
			{ 
				temp.append(str); 
			} 
		} 
		raf.skipBytes(2*(nameSize-i)); 
		return temp.toString(); 
	} 

	public int readAge(RandomAccessFile raf)throws Exception 
	{ 
		return raf.readInt(); 
	} 
}//end class
