RandomAccessFile主要功能是随机读取,可以读取指定位置的内容,可以跳过指定的字节数读取
- package com.zzh.io;
- import java.io.File;
- import java.io.IOException;
- import java.io.RandomAccessFile;
- public class RandomAccessFileDemo {
- /**
- * RandomAccessFile主要功能是随机读取,可以读取指定位置的内容,可以跳过指定的字节数读取
- */
- public static void main(String[] args) throws IOException {
- testWrite();
- testRead();
- }
- private static void testWrite() throws IOException {
- File file = new File("D:" + File.separator + "test.txt");
- //RandomAccessFile的构造函数的第1个参数表示文件,
- //第2个参数表示文件打开的模式,常用有3种:r,w,rw
- //rw:如果文件不存在,会自动创建
- RandomAccessFile raf = new RandomAccessFile(file, "rw");
- String name = null;
- int age = 0;
- name = "zhangsan";
- age = 18;
- raf.writeBytes(name);
- raf.writeInt(age);
- name = "lisi ";//这里要补全空格,使字符串为8位,否则读取时会出错
- age = 19;
- raf.writeBytes(name);
- raf.writeInt(age);
- name = "wangwu ";//这里要补全空格,使字符串为8位,否则读取时会出错
- age = 20;
- raf.writeBytes(name);
- raf.writeInt(age);
- raf.close();//关闭资源文件,切记!
- }
- private static void testRead() throws IOException {
- File file = new File("D:" + File.separator + "test.txt");
- RandomAccessFile raf = new RandomAccessFile(file, "r");
- String name = null;
- int age = 0;
- byte[] b = new byte[8];
- raf.skipBytes(12);//跳过第一个人的12个字节,读第二个人的信息
- for (int i = 0; i < b.length; i++) {
- b[i] = raf.readByte();//读取一个字节
- }
- name = new String(b);
- age = raf.readInt();
- System.out.println("第二个人的姓名:" + name + ", 年龄:" + age);
- raf.seek(0);//将指针定位回文件开始处,读第一个人的信息
- for (int i = 0; i < b.length; i++) {
- b[i] = raf.readByte();//读取一个字节
- }
- name = new String(b);
- age = raf.readInt();
- System.out.println("第一个人的姓名:" + name + ", 年龄:" + age);
- raf.seek(24);//将指针定位到第三个人处,读第三个人的信息
- // raf.skipBytes(12);//空出第二个人的信息,读第三个人的信息
- for (int i = 0; i < b.length; i++) {
- b[i] = raf.readByte();//读取一个字节
- }
- name = new String(b);
- age = raf.readInt();
- System.out.println("第三个人的姓名:" + name + ", 年龄:" + age);
- raf.close();//关闭资源文件,切记!
- }
- }