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

📄 randomfiletest.java

📁 孙鑫JAVA从入门到精通配套练习程序。所有程序都实际运行过
💻 JAVA
字号:
//演示RandomAccessFile类的用法
import java.io.*;
class RandomFileTest
{
	public static void main(String[] args) throws FileNotFoundException, IOException
	{
		Student s1 = new Student(1, "zhangshan", 98.5);
		Student s2 = new Student(2, "lisi", 96.5);
		Student s3 = new Student(3, "wangwu", 90.5);
		RandomAccessFile raf = new RandomAccessFile("Student.txt", "rw");
		s1.write(raf);
		s2.write(raf);
		s3.write(raf);
		
		raf.seek(0);
		Student s = new Student();
		for(long i=0; i<raf.length(); i=raf.getFilePointer())
		{
			s.read(raf);
			System.out.println(s.num + ":" + s.name + ":" + s.score);
		}
		raf.close();
	}
}

class Student
{
	int num;
	String name;
	double score;
	Student()
	{
	}
	Student(int num, String name, double score)
	{
		this.num = num;
		this.name = name;
		this.score = score;
	}
	void write(RandomAccessFile raf) throws IOException
	{
		raf.writeInt(num);
		raf.writeUTF(name);
		raf.writeDouble(score);
	}
	void read(RandomAccessFile raf) throws IOException
	{
		num = raf.readInt();
		name = raf.readUTF();
		score = raf.readDouble();
	}
}

⌨️ 快捷键说明

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