RAF(RandomAccessFile)类

作用:读取文件

/**
 * 
 */
package com.io.file;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

/**
 * <pre>
 * <b>.</b>
 * <b>Description:</b> 
 *    RandomAccessFile:随机读写文件类
 *      读写:文件的写入,只写入一个byte,从后八位写入 读,只读一个byte,读完后,指针自动指向下一个byte
 *          文件读写完成后一定关闭
 *      模式:两种:rw、r
 *      关闭:文件用完即关
 * <b>Author:</b> @xieji
 * <b>Date:</b> 2016年11月14日 下午2:19:21
 * <b>Copyright:</b> Copyright ©2013-2017  https://github.com/Jacob233 (github主页 0.0)
 * <b>Changelog:</b>
 *   Ver   Date                         Author                   Detail
 *   --------------------------------------------------------------------------------
 *   1.0   2016年11月14日 下午2:19:21              @xieji
 * </pre>
 */
public class RAFDemo {
    // 随机读写文件测试
    public void testRAF() throws IOException {
        File demo = new File("demo");
        // 判断file是否存在,若不存在则创建
        if (!demo.exists()) {
            demo.mkdir();
        }
        // 判断file是否存在文件,若不存在则创建
        File content = new File(demo, "raf.txt");
        if (!content.exists()) {
            content.createNewFile();
        }
        // 获取读写文件类randomAccessFile(模式为读写rw,还有一种模式是r)
        RandomAccessFile raf = new RandomAccessFile(content, "rw");
        // raf通过指针实现随机读写
        System.out.print(raf.getFilePointer() + " ");// 初始指针
        // 写入(指针在移动)
        raf.write('A');
        System.out.print(raf.getFilePointer() + " ");
        raf.write('B');
        System.out.print(raf.getFilePointer() + " ");
        // 1.写入整形 :写入只能从后八位,测试通过int最大数
        int maxInt = 0x7fffffff;
        raf.write(maxInt >>> 24 & 0xff);// 向右移动24位,即高八位
        raf.write(maxInt >>> 16 & 0xff);
        raf.write(maxInt >>> 8 & 0xff);
        raf.write(maxInt >>> 0 & 0xff);
        // 上述代码,可用下面的一行代替
        // raf.writeInt(maxInt);
        System.out.print(raf.getFilePointer() + " ");
        // 2.写入字符串
        String word = "谢ji";

        byte b[] = word.getBytes("gbk");
        raf.write(b);
        System.out.println(raf.length());
        System.out.print(raf.getFilePointer() + " ");

        raf.writeChars(word);
        System.out.print(raf.getFilePointer() + " ");
        System.out.println();
        // 读取文件
        byte[] bytes = new byte[(int) raf.length()];
        // 先将指针只会头节点
        raf.seek(0);
        raf.read(bytes);
        System.out.println(Arrays.toString(bytes));
        // for (byte c : bytes) {
        // System.out.print(Integer.toHexString(c&0xff)+" ");
        // }
        // 关闭
        raf.close();
    }
}
原文地址:https://www.cnblogs.com/xieji233/p/6155604.html