RandomAccessFile可以实现两个作用
1.实现对一个文件做读和写的操作
2.可以访问文件的任意位置,不像其他流只能按照先后顺序读取。
三个核心方法:
1.RandomAccessFile(String name,String mode) name用来确定文件,mode取r(读)或rw(可读写),通过mode可以确定流对文件的访问权限。
2.seek(long a)用来定位流对象读写文件的位置,a确定读写位置距离文件开头的字节个数
3.getFilePointer()获得流的当前读写位置
import java.io.*;
public class RandomAccessFileDemo {
public static void main(String[] args) {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile("d:/eeeeeeee.txt","rw");
//将若干数据写入到文件中
int[] arr = new int[] {10,20,30,40,50,60,70,80,90,100};
for(int i=0;i<arr.length;i++) {
raf.writeInt(arr[i]);
}
raf.seek(4);
System.out.println(raf.readInt());
//隔一个读一个数据
for(int i=0;i<10;i+=2) {
raf.seek(i*4);
System.out.print(raf.readInt()+"\t");
}
System.out.println();
//在第8个字节位置插入一个新的数据45,替换以前的数据30
raf.seek(8);
raf.writeInt(45);
for(int i=0;i<10;i+=2) {
raf.seek(i*4);
System.out.print(raf.readInt()+"\t");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(raf!=null) {
raf.close();
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
}