java==IO=随机读写文件

/**
 * RandomAccessFile:不是IO四大体系中的子类;
 * 特点:
 * 1、该对象即能读又能写。
 * 2、该对象内部维护一个byte【】数组并通过指针可以操作数组中的元素;
 * 3、数组可变,指针可以根据getFilePointer方法获取指针的位置,和通过seek方法设置指针的位置;
 * 4、其实该对象就是将字节输入流和输出流进行了封装。
 * 5、构造方法只能接受File对象或者字符串路径以及权限模式
 */
package 随机读取写入文件;

import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @author Administrator
 *
 */
public class RandomAccessFileDemo {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {

        
        //writeFile();
        //readFile();
        randomWrite();
        
    }

    public static void randomWrite() throws IOException {
        RandomAccessFile raf = new RandomAccessFile("random.txt", "wr");
        //因为每组数据都是8个字节存储的,使用此类数据一般都是有规律的,所以必须是8的倍数,同时应用于多线程作用于同一个文件;也可以用于下载文件的时候断点续传;其它流做不到;
        raf.seek(2*8);
        raf.write("赵六".getBytes());
        raf.writeInt(56);
        raf.close();
    }

    public static void readFile() throws IOException {
        RandomAccessFile raf = new RandomAccessFile("random.txt", "r");
        //通过seek方法设置指针,实现随机读取,只要明确指针位置即可;
        raf.seek(1*8);//从第八个字节开始读
        byte[]arr = new byte[4];
        raf.read(arr);//读取数据4个字节存入数组arr
        String name = new String(arr);//将保存4个字节的byte数组转成字符串
        int age = raf.readInt();//再次读取4个字节;存入arr数组;
        System.out.println(name+":"+age);
        System.out.println("pos"+raf.getFilePointer());
        raf.close();
    }

    public static void writeFile() throws IOException {
        RandomAccessFile raf = new RandomAccessFile("random.txt", "rw");
        //如果文件存在不创建,如果文件不存在创建;
        raf.write("张三".getBytes());
        //raf.write(97);//去掉高八位,不能保证数据原样性;
        raf.writeInt(69);//四个字节写Int数据,保证数据原样性;
        raf.write("小强".getBytes());
        raf.writeInt(98);
        raf.close();
    }

}
原文地址:https://www.cnblogs.com/wangyinxu/p/6859316.html