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;
}
}
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;
}
}
相关文章推荐
- 入门训练 圆的面积
- 从零开始写javaweb框架笔记7-动手开发web应用
- setNeedsDisplay setNeedsLayout layoutIfNeeded
- 【SDOI2013】淘金
- 多媒体开发之rtmp---rtmp client 编译
- 判断一个字符串里是否含有某段字符?怎么截取一段字符?
- 10018---jQuery--遍历
- 解一元二次方程
- java.io.Serializable接口
- Brackets安装Emmet插件显示“Internal error”解决办法
- 开始学习Python,设置环境和编译一个简单的程序
- 规定时间内,生产随机数不变rand()
- 程序闪退情景一
- 恒拓开源笔试题
- 入门训练 Fibonacci数列
- 贪吃蛇
- windows下程序的命名习惯和Linux下程序的命名习惯对比
- 一个正则表达式分析(python)
- eclipse 快捷键
- 趣味C语言