(原创)RandomAccessFile随机读取流

    xiaoxiao2026-05-07  1

    前言

    RandomAccessFile是属于随机读取类,是可以对文件本身的内容直接随机进行操作的,可以在文件的指定位置 的读取和写入内容,这在很多时候都是很方便的。

    1. 写入文件

    public void write(View view) { String fileName = getFilesDir() + "/test.txt"; String insertContent = "1234567890123456789012345678901234567890123456789012345678901234567890" + "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" + "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" + "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; try { File file = new File(fileName); RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.write(insertContent.getBytes()); raf.close(); System.out.println("File length: " + new File(fileName).length()); } catch (Exception e) { } }

    3. 读取文件

    public void read(View view) { String fileName = getFilesDir() + "/test.txt"; try { RandomAccessFile raf = new RandomAccessFile(fileName, "r"); // 需要读取的文件的大小 System.out.println("raf.length(): " + raf.length()); // 从第11字节开始读取 int start = 10; raf.seek(start); // 跳过2个字节读取 raf.skipBytes(2); // 每次读取的字节数 byte[] bytes = new byte[1024]; int byteRead ; while ((byteRead = raf.read(bytes)) != -1) { System.out.println(new String(bytes, 0, byteRead)); } raf.close(); } catch (Exception e) { e.printStackTrace(); } }

    效果图:

    转载请注明原文地址: https://ju.6miu.com/read-1309435.html
    最新回复(0)