java中RandomAccessFile类用法

本文介绍了如何使用Java的RandomAccessFile类进行文件的随机访问操作,包括读写等长记录文件的优势及实例演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

RandomAccessFile类
    只能访问文件,不能操作其他io设备
    支持随机访问
    在读写等长记录文件有优势

实例:

import java.io.*;

class Employee {
	private String name;
	private int age;
	public static final int LEN = 8;
	
	String getName() {
		return name;
	}
	
	int getAge() {
		return age;
	}
	
	Employee(String name, int age) {
		if (name.length() > LEN) { // 为了构造等长记录
			this.name = name.substring(0, LEN-1);
		} else {
			this.name = name;
			while (this.name.length() < LEN) {
				this.name += '\u0000';
			}
		}
		this.age = age;
	}
}

public class RandomAccessFileTest {
	public static void main(String [] args) {
		Employee e1 = new Employee("Ronnie", 37);
		Employee e2 = new Employee("John", 37);
		Employee e3 = new Employee("Mark", 37);
		
		try {
			RandomAccessFile randFile = new RandomAccessFile("employee.txt", "rw");
			
			//randFile.write(e1.getName().getBytes()); // 如果name有中文,会出现问题,因为一个英文字符转换为一个字节,一个中文字符转换为两个字节,可以用writeChars函数改写
			randFile.writeChars(e1.getName()); //-
			randFile.writeInt(e1.getAge());
			//randFile.write(e2.getName().getBytes());
			randFile.writeChars(e1.getName()); //-
			randFile.writeInt(e2.getAge());
			//randFile.write(e3.getName().getBytes());
			randFile.writeChars(e1.getName()); //-
			randFile.writeInt(e3.getAge());
			
			randFile.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		try {
			//byte[] nameBuf = new byte[Employee.LEN];
			
			RandomAccessFile randFile = new RandomAccessFile("employee.txt", "r");
			
			//randFile.skipBytes(12);
			randFile.skipBytes(20); //-
			//int len = randFile.read(nameBuf);
			//String name = new String(nameBuf, 0, len);
			String name = "";//-
			for (int i = 0; i < Employee.LEN; ++i) { //-
				name += randFile.readChar(); //-
			}//-
			System.out.println(name.trim() + ":" + randFile.readInt());
			name = ""; //-
			
			randFile.seek(0); // 绝对定位
			//len = randFile.read(nameBuf);
			//name = new String(nameBuf, 0, len);
			for (int i = 0; i < Employee.LEN; ++i) { //-
				name += randFile.readChar(); //-
			} //-
			System.out.println(name.trim() + ":" + randFile.readInt());
			name = ""; //-
			
			//randFile.skipBytes(12);
			randFile.skipBytes(20); //-
			//len = randFile.read(nameBuf);
			//name = new String(nameBuf, 0, len);
			for (int i = 0; i < Employee.LEN; ++i) { //-
				name += randFile.readChar(); //-
			} //-
			System.out.println(name.trim() + ":" + randFile.readInt());
			
			randFile.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


注释部分为按字节写入时的程序,带//-为原来的代码

其他函数请参照jdk文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值