永发信息网

谁能给我举个例子RandomAccessFile类

答案:1  悬赏:80  手机版
解决时间 2021-07-21 03:06
  • 提问者网友:别再叽里呱啦
  • 2021-07-20 07:46
谁能给我举个例子RandomAccessFile类
最佳答案
  • 五星知识达人网友:一秋
  • 2021-07-20 08:42

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<raf.length();i=raf.getFilePointer())
{
s.read(raf);
System.out.println("[lenth:"+raf.length()+",i="+i+"] " + s);
}
raf.close();
Thread.sleep(5000);
}
}


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

我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯