RandomAccessFile 可以实现两个作用:

    1. 实现对一个文件做读和写的操作。
    2. 可以访问文件的任意位置。不像其他流只能按照先后顺序读取

      在开发某些客户端软件时,经常用到这个功能强大的可以”任意操作文件内容”的类。比 如,软件的使用次数和使用日期,可以通过本类访问文件中保存次数和日期的地方进行比对 和修改。 Java 很少开发客户端软件,所以在 Java 开发中这个类用的相对

      学习这个流需掌握三个核心方法 :

    3. RandomAccessFile(String name, String mode) name 用来确定文件; mode 取 r(读)或 rw(可读写),通过 mode 可以确定流对文件的

    4. seek(long a) 用来定位流对象读写文件的位置,a 确定读写位置距离文件开头的字节个数
    5. getFilePointer() 获得流的当前读写位置
    1. import java.io.RandomAccessFile;
    2. public class RandomAccessFileDemo {
    3. public static void main(String[] args) {
    4. RandomAccessFile randomAccessFile=null;
    5. try{
    6. randomAccessFile=new RandomAccessFile("d:/javaStudy/javaworkspace/random.txt","rw");
    7. //将若干数据写到文件中
    8. int[] arr=new int[]{10,20,30,40,50,60,70,80,90,100};
    9. for(int i=0;i<arr.length;i++){
    10. randomAccessFile.writeInt(arr[i]);
    11. }
    12. randomAccessFile.seek(4); //从指定字节位置开始读,默认0
    13. System.out.println(randomAccessFile.readInt());
    14. //间隔读取数据
    15. for(int i=0;i<10;i+=2){
    16. randomAccessFile.seek(i*4);
    17. System.out.print(randomAccessFile.readInt()+"\t");
    18. }
    19. System.out.println();
    20. //在第八个字节位置插入一个新的数据45,替换之前的数据30
    21. randomAccessFile.seek(8);
    22. randomAccessFile.writeInt(45);
    23. for(int i=0;i<10;i+=2){
    24. randomAccessFile.seek(i*4);
    25. System.out.print(randomAccessFile.readInt()+"\t");
    26. }
    27. }catch (Exception e){
    28. e.printStackTrace();
    29. }finally {
    30. try{
    31. if(randomAccessFile!=null){
    32. randomAccessFile.close();
    33. }
    34. }catch (Exception e){
    35. e.printStackTrace();
    36. }
    37. }
    38. }
    39. }