⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 rafdemo.java

📁 JSP课程设计案例精编 源代码 共有12个哦 解说详细
💻 JAVA
字号:
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

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -