您的位置:首页 > 其它

RandomAccessFile

2015-12-05 23:13 309 查看
package com.company.project;

import java.io.IOException;
import java.io.RandomAccessFile;
import com.company.project.Student;;

public class RandomAccessFileTest {
public static void main(String[] args) throws IOException {
RandomAccessFile raf = new RandomAccessFile("D://cola//jing.txt","rw");
Student student1 = new Student();
Student student2 = new Student();

student1.setId(11);
student1.setName("jia");
student1.setScore(99f);

student2.setId(11);
student2.setName("jing");
student2.setScore(99f);

writeFile(raf, student1);
writeFile(raf, student2);
System.out.println(readFile(raf, 0));
System.out.println(readFile(raf, raf.getFilePointer())); //getFilePointer() 返回当前指针的偏移位置 返回类型long
raf.close();

}

public static void writeFile(RandomAccessFile raf, Student student) throws IOException{

raf.writeInt(student.getId());
raf.writeUTF(student.getName());
raf.writeFloat(student.getScore());
}
public static Student readFile(RandomAccessFile raf,long pos) throws IOException{
Student student = new Student();
raf.seek(pos);
student.setId(raf.readInt());
student.setName(raf.readUTF());
student.setScore(raf.readFloat());

return student;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: