RandomAccessFile 类的主要功能成随机的读取操作,本身也可以直接向文件中保存内容
如果要想实现随机读取,则在存储数据的时候要保证 数据长度的一致性,否则是无法实现功能的。
RandomAccessFile 的构造方法
public RandomAccessFile(File file,String mode) throws FileNotFoundException
需要接收一个File 类的实例,并设置一个操作的模式:
读模式:r
写模式:w
读写模式:rw
其中最重要的是读写模式,如果操作的文件不存在,则会帮用户自动创建
使用RandomAccessFile 进行写入的操作
使用从DataOutput接口中实现的一系列的writeXXX()方法写入数据
package org.randomaccessfile;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileDemo01 {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException { //所有异常抛出
// TODO Auto-generated method stub
File file = new File("D:"+File.separator+"demo.txt"); //指定要操作的文件
RandomAccessFile raf = new RandomAccessFile(file,"rw"); //以读写的形式进行操作
//写入第一条数据
String name = "Zhangsan"; //表示姓名
int age = 20; //表示年龄
raf.writeBytes(name); //以字节的方式将字符串写入
raf.writeInt(age); //写入整形数据
//写入第二条数据
name = "lisi "; //表示姓名
age = 21; //表示年龄
raf.writeBytes(name);
raf.writeInt(age);
name = "wangwu ";
age = 22;
raf.writeBytes(name);
raf.writeInt(age);
raf.close(); //文件操作的最后一定要关闭
}
}
使用RandomAccessFile 进行读取的操作
在RandomAccessFile 操作的时候读取的方法都是从DataInput 接口实现而来,有一系列的readXXX()方法,可以读取各种类型的数据
但是在RandomAccessFile 中因为可以实现随机的读取,所以有一系列的控制方法
回到读取点:public void seek(long pos) throws IOException
跳过多少个字节:public int skipBytes(int n) throws IOException
下面就进行读取的操作:
package org.randomaccessfile;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
public class RandomAccessFileDemo02 {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception { //所有异常抛出
// TODO Auto-generated method stub
File file = new File("D:"+File.separator+"demo.txt"); //指定要操作的文件
RandomAccessFile raf = new RandomAccessFile(file,"r"); //以读的形式进行操作
byte bt[] = new byte[8]; //定义字节数组
int age = 0;
raf.seek(12); //跨过第一个人的信息
for (int i=0;i<8;i++){
bt[i] = raf.readByte(); //读取字节
}
age = raf.readInt();
System.out.println("姓名:"+new String(bt)+"年龄:"+age);
raf.seek(0); //回到开始位置
for (int i=0;i<8;i++){
bt[i] = raf.readByte(); //读取字节
}
age = raf.readInt(); //读取数字
System.out.println("姓名:"+new String(bt)+"年龄:"+age);
raf.skipBytes(12); //跨过第二个人的信息
for (int i=0;i<8;i++){
bt[i] = raf.readByte();
}
age = raf.readInt();
System.out.println("姓名:"+new String(bt)+"年龄:"+age);
raf.close(); //文件操作的最后一定要关闭
}
}