RandomAccessFile:提供的对文件内容的访问,既可以读文件,也可以写文件;支持随机访问文件,可以访问文件的任何位置
- 打开文件有两种模式 “rw”(读写) 和“r”(只读),RandomAccessFile raf = new RandomAccessFile(file, “rw”);
- raf.seek(0);//定位指针位置,读取文件初始值是0,从开头读取
- 写方法raf.write(char) –>只写一个字节(后8位),同时指针指向下一个位置,准备再次写入
- 读方法int b = raf.read() –> 只读一个字节
- 文件读写完成之后一定要关闭,避免出现一些异常情况
RandomAccessFile示例
File file = new File(path, fileName);
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
//打印指针
System.out.println("文件指针初始:" + randomAccessFile.getFilePointer());
//写入
randomAccessFile.write('b');//每次写入一个字节
//randomAccessFile.writeBytes("郑海龙");//用writeBytes写入中文,默认用ansi编码
//randomAccessFile.write("萨达".getBytes());默认用项目的编码
randomAccessFile.seek(0);
byte[] buff = new byte[1];
String s1 = new String(buff); System.out.print(s1);
randomAccessFile.seek(1);
byte[] buff2 = new byte[9];
randomAccessFile.read(buff2);
System.out.println(s2);