1.RandomAccessFile:什么是 随机读写流RandomAccessFile???随机读写流RandomAccessFile常用方法有哪些???

    技术2022-07-16  68

    1.RandomAccessFile:什么是 随机读写流RandomAccessFile???随机读写流RandomAccessFile常用方法有哪些???

    学习:第7遍


    1.什么是 随机读写流RandomAccessFile???

    随机读写流,是一个字节流,可以对文件进行随机读写 随机:可以定位到文件的任意位置进行读写操作,通过移动指针(Pointer)来实现 读写:使用该流既能读取文件,也能写入文件


    2. 随机读写流RandomAccessFile常用方法有哪些???

    创建:RandomAccessFile raf=new RandomAccessFile(“a.txt”,“rw”) 第二个参数是模式:r只读、rw读写 当文件不存在时: 如果模式为r,会报异常FileNotFoundException 如果模式为rw,会自动创建文件

    方法:raf.getFilePointer() 作用;获取当前指针的位置,从0开始

    方法:raf.seek(8) 作用; 将指针移动到指定的位置

    方法:raf.skipBytes(3) 作用:将指针向后跳过指定的字节,只能往前,不能倒退 ——>


    public class TestRandomAccessFile { public static void main(String[] args) { try( /* * 创建:RandomAccessFile raf=new RandomAccessFile("a.txt","rw") * 模式:r只读、rw读写 * 当文件不存在时: * 如果模式为r,会报异常FileNotFoundException * 如果模式为rw,会自动创建文件 */ RandomAccessFile raf=new RandomAccessFile("a.txt", "rw"); ){ /** * 方法:raf.getFilePointer() * 作用;获取当前指针的位置,从0开始 */ System.out.println(raf.getFilePointer()); //对于utf-8,一个汉字占3个字节 raf.write("张三".getBytes()); raf.write("hello".getBytes()); System.out.println(raf.getFilePointer()); // 11 System.out.println("写入成功"); /** * 方法:raf.seek(8) * 作用; 将指针移动到指定的位置 */ raf.seek(8); // raf.write("李四".getBytes()); System.out.println(raf.getFilePointer()); // 14 raf.seek(6); byte[] buffer=new byte[2]; raf.read(buffer); System.out.println(new String(buffer)); System.out.println(raf.getFilePointer()); // 8 /** * 方法:raf.skipBytes(3) * 作用:将指针向后跳过指定的字节,只能往前,不能倒退 ——> */ raf.skipBytes(3); buffer=new byte[1024*1024]; int num=-1; while((num=raf.read(buffer))!=-1){ System.out.println(new String(buffer,0,num)); } // 修改数据 raf.seek(8); raf.write("赵".getBytes()); System.out.println("修改成功"); }catch(IOException e){ e.printStackTrace(); } } }
    Processed: 0.012, SQL: 9