RandomAccessFile

版权声明:正在学习中,有错误欢迎指出。感谢比❤❤~ https://blog.csdn.net/gx17864373822/article/details/79972674
import java.io.*;
import java.util.Arrays;

public class Main {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        int [] data = {1,2,3,4,5,6,7,8,9,10};
        RandomAccessFile raf = new RandomAccessFile("data.dat", "rw");//可读可写

        //写
        for(int i = 0; i < data.length; i++){
            raf.writeInt(data[i]);
        }

        //读
        System.out.println(raf.getFilePointer());//4(字节)*10(个)
        raf.seek(0);//调整指针
        for(int i = 0; i < data.length; i++){
            int read = raf.readInt();
            System.out.print(read + "-----");
            System.out.println(raf.getFilePointer());
        }
        System.out.println();

        //想找7
        raf.seek((7-1)*4);//找到写7之前的指针位置
        System.out.println(raf.readInt());
        System.out.println();

        //再写入17
        raf.writeInt(17);
        raf.seek(0);
        for(int i = 0; i < data.length; i++){//看17是否写入
            int read = raf.readInt();
            System.out.print(read + "-----");
            System.out.println(raf.getFilePointer());
        }

        raf.close();
    }

}

输出:

40
1-----4
2-----8
3-----12
4-----16
5-----20
6-----24
7-----28
8-----32
9-----36
10-----40

7

1-----4
2-----8
3-----12
4-----16
5-----20
6-----24
7-----28
17-----32
9-----36
10-----40
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页