Java IO RandomAccessFile

RandomAccessFile 是随机访问文件(包括读/写)的类。它支持对文件随机访问的读取和写入,即我们可以从指定的位置读取/写入文件数据。

例子1:

package io.stream;

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

public class RandomAccessFileTest {
    private File file = null;

    public static void main(String[] args) {
        RandomAccessFileTest rand = new RandomAccessFileTest();
        rand.init();
        // 写入信息到文件中
        rand.record("zhangsan", 56);
        rand.record("wangwu", 56);
        // 打印文件信息
        System.out.println("用户信息如下:");
        rand.print();
        // 修改zhangsan的成绩
        rand.record("zhangsan", 87);
        // 打印文件信息
        System.out.println("\n修改后用户信息如下:");
        rand.print();
    }

    /**
     * 初始化文件对象
     */
    public void init() {
        if ( null == file ) {
            file = new File("document/record.txt");
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将用户和成绩写入到文件中
     * @param name 用户名
     * @param score 成绩
     */
    public void record(String name, int score) {
        RandomAccessFile rand = null;
        try {
            rand = new RandomAccessFile(file, "rw");

            // 用户是否存在,true-存在,false-不存在
            boolean flag = false;

            while ( rand.getFilePointer() < rand.length() ) {
                String tempName = rand.readUTF();

                if ( name.equals(tempName) ) {
                    // 如果用户存在,则更新用户的成绩
                    rand.writeInt(score);
                    flag = true;
                    break;
                } else {
                    // 如果用户不存在,则跳过用户的成绩进入下一个用户
                    rand.skipBytes( Integer.SIZE / 8 );
                }
            }

            // 如果用户不存在则新增
            if ( !flag ) {
                rand.writeUTF(name);
                rand.writeInt(score);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if ( null != rand ) {
                try {
                    rand.close();
                    rand = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 输出文件信息
     */
    public void print() {
        RandomAccessFile rand = null;
        try {
            rand = new RandomAccessFile(file, "r");
            while ( rand.getFilePointer() < rand.length() ) {
                String name = rand.readUTF();
                int score = rand.readInt();
                System.out.println("name:" + name + " score:" + score);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if ( null != rand ) {
                try {
                    rand.close();
                    rand = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

例子2:

package com.louisgeek.appupdatetool;

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

/**
 * Created by louisgeek on 2016/8/23.
 */
public class RandomAccessFileTest {

    private static final String FileName = "file.txt";

    public static void main(String[] args) {
        // 若文件“file.txt”存在,则删除该文件。
        File file = new File(FileName);
        if (file.exists())
            file.delete();

        testCreateWrite();
        testAppendWrite();
        testRead();
    }

    /**
     * 若“file.txt”不存在的话,则新建文件,并向文件中写入内容
     */
    private static void testCreateWrite() {
        try {
            // 创建文件“file.txt”对应File对象
            File file = new File(FileName);
            // 创建文件“file.txt”对应的RandomAccessFile对象
            RandomAccessFile raf = new RandomAccessFile(file, "rw");

            // 向“文件中”写入26个字母+回车
            raf.writeChars("abcdefghijklmnopqrstuvwxyz\n");
            // 向“文件中”写入"9876543210"+回车
            raf.writeChars("9876543210\n");

            raf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 向文件末尾追加内容
     */
    private static void testAppendWrite() {
        try {
            // 创建文件“file.txt”对应File对象
            File file = new File(FileName);
            // 创建文件“file.txt”对应的RandomAccessFile对象
            RandomAccessFile raf = new RandomAccessFile(file, "rw");

            // 获取文件长度
            long fileLen = raf.length();
            // 将位置定位到“文件末尾”
            raf.seek(fileLen);

            // 以下向raf文件中写数据
            raf.writeBoolean(true); // 占1个字节
            raf.writeByte(0x41);    // 占1个字节
            raf.writeChar('a');     // 占2个字节
            raf.writeShort(0x3c3c); // 占2个字节
            raf.writeInt(0x75);     // 占4个字节
            raf.writeLong(0x1234567890123456L); // 占8个字节
            raf.writeFloat(4.7f);  // 占4个字节
            raf.writeDouble(8.256);// 占8个字节
            raf.writeUTF("UTF严"); // UTF-8格式写入
            raf.writeChar('\n');   // 占2个字符。“换行符”

            raf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过RandomAccessFile读取文件
     */
    private static void testRead() {
        try {
            // 创建文件“file.txt”对应File对象
            File file = new File(FileName);
            // 创建文件“file.txt”对应的RandomAccessFile对象,以只读方式打开
            RandomAccessFile raf = new RandomAccessFile(file, "r");

            // 读取一个字符
            char c1 = raf.readChar();
            System.out.println("c1=" + c1);
            // 读取一个字符
            char c2 = raf.readChar();
            System.out.println("c2=" + c2);

            // 跳过54个字节。
            raf.seek(54);

            // 测试read(byte[] buffer, int byteOffset, int byteCount)
            byte[] buf = new byte[20];
            raf.read(buf, 0, buf.length);
            System.out.println("buf=" + (new String(buf)));

            raf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

版权声明:本文为RichieZhu原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。