早教吧 育儿知识 作业答案 考试题库 百科 知识分享

谁能给我举个例子RandomAccessFile类

题目详情
谁能给我举个例子RandomAccessFile类
▼优质解答
答案和解析
RandomAccessFile类用处还是很大的,读写文件非常方便,指针又可以任意移动,这里有个写入和读取的例子供你参考,你可以直接拷贝去编译和运行,慢慢体会一下: import java.io.IOException; import java.io.File; import java.io.RandomAccessFile; class RandomFileTest { public static void main(String[] args) throws Exception { Student s1=new Student(1, "zhangsan", 90.5); Student s2=new Student(2, "lisi", 98.5); Student s3=new Student(3, "wangwu", 96.5); File userDir=new File(System.getProperties().getProperty("user.dir")); File tempFile=File.createTempFile("~student", ".tmp", userDir); tempFile.deleteOnExit(); RandomAccessFile raf=new RandomAccessFile(tempFile, "rw"); s1.write(raf); s2.write(raf); s3.write(raf); raf.seek(0); Student s=new Student(); for(long i=0;i