4.RandomAccessFile类

文章目录

RandomAccessFile类

//RandomAccessFile的演示
public class RandomAccessFileDemo {
	public static void main(String[] args) throws IOException {
		//创建文件路径字符串
		String file = "D:/java.java";
		writeFile(file);
		readFile(file);
	}
	//
	private static void readFile(String file) throws IOException   {
		//创建具有读权限的RanddomAccessFile对象,注意需要抛出找不到文件异常FileNotFoundException
		RandomAccessFile raf = new RandomAccessFile(file,"r");
		//返回当前偏移量,主要要抛出IOExcepiton
		System.out.println("当前偏移量" + raf.getFilePointer());
		StringBuilder sb = new StringBuilder();
		//既读取zhangsan
		for (int i = 0; i < 8; i++) {
			//readByte()为从文件读取一个有符号的八位值.
			sb.append((char)raf.readByte());
		}
		System.out.println("name :" + sb);
		
		System.out.println("当前偏移量" + raf.getFilePointer());
		//返回一个4个字节的int类型
		System.out.println("age= " + raf.readInt());
		//跳过八个字节,既跳过 "huangkuh"
		raf.skipBytes(8);
		//读取kunhuang
		for (int i = 0; i < 8; i++) {
			sb.append((char)raf.readByte());
		}
		
		System.out.println("name:" + sb);
		System.out.println("当前偏移量" + raf.getFilePointer());
		System.out.println("age:" + raf.readInt());
		//关闭
		raf.close();
	}
	//往文件写入数据
	private static void writeFile(String file) throws IOException {
		//创建具有读写权限的RandomAccessFile对象,注意需要抛出找不到文件异常
		RandomAccessFile raf = new RandomAccessFile(file,"rw");
		//wtite写入字符串,参数为byte数组,注意需要抛出IO异常
		raf.write("zhangsan".getBytes());
		//write按四个字节写入整型,
		raf.writeInt(11);
		
		raf.write("huangkuh".getBytes());
		raf.writeInt(23);
		
		raf.write("kunhuang".getBytes());
		raf.writeInt(34);
		//关闭
		raf.close();		
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值