一.随机读写流的介绍
- RandomAccessFile-随机读写流,不属于任何流对象,直接继承了Object类,既可读又可写可随机访问读和写
- 以前学的流对象 读取从文件开头读,写末尾追加或开头覆盖
- RandomAccessFile在文件任意位置上开始读和写,隐含了大型字节数组,文件都是由字节组成,文件二进制都放在自己的数组中
- 有一种游标或索引到隐含数组中,称为文件指针
- 输入操作从文件指针开始读取字节,并使文件指针超过读取的字节数。 如果在读/写模式下创建随机访问文件,则输出操作也可用;
- 输出操作从文件指针开始写入字节,并使文件指针超过写入的字节。 写入隐含数组当前末尾的输出操作会导致数组被扩展。 文件指针可以通过读取-getFilePointer方法和设置-seek方法。
- seek(long l) 设置开始的指针
- rw.skipBytes() 跳过字节数,调用了seek方法
- 构造器:
- 1)RandomAccessFile(File file, String mode)
- 创建一个随机访问文件流读,随意写来,由 File参数指定的文件。
- 2)RandomAccessFile(String name, String mode)
- 创建一个随机访问文件流,并可选择地写入到具有指定名称的文件中。
- 模式:r 只读 如果写会抛异常
- 模式:rw 可读可写
- 常应用于多线程下载大文件
二.代码案例
package InputOutput;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomDemo {
public static void write() throws IOException {
RandomAccessFile rw = new RandomAccessFile("random.txt", "rw");
rw.write("张三".getBytes());
rw.write(65);
rw.seek(16);
rw.write("李四".getBytes());
rw.write(66);
rw.seek(8);
rw.write("王五".getBytes());
rw.write(67);
rw.close();
}
public static void read() throws IOException {
RandomAccessFile rw = new RandomAccessFile("random.txt", "rw");
while(true) {
try {
byte[] bytes = new byte[4];
int len = rw.read(bytes);
System.out.println(new String(bytes));
int age = rw.readInt();
System.out.println(age);
}catch (Exception e){
break;
}
rw.close();
}
}
public static void main(String[] args) throws IOException {
read();
}
}