16.6 RandomAccessFile

RandomAccessFile可以实现文件数据的随机读取,即:通过对文件内部读取位置的自由定义,以实现部分数据的读取操作,所以在使用此类操作时就必须保证写入数据时数据格式与长度统一
在这里插入图片描述
在这里插入图片描述
范例:使用RandomAccessFile写入数据

package com.lxh.sixteenchapter;

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

public class JavaIODemo421 {
       public static void main(String[] args) {
		File file=new File("E:"+File.separator+"File"+File.separator+"ll.txt");
		if(!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			RandomAccessFile raf=new RandomAccessFile(file,"rw");
			//要保存的姓名数据,为保证长度一致,使用空格填充
			String name[]=new String[]{"zhangsan","lisi    ","wangwu  "};
			int age[]=new int [] {17,23,40};
			//循环写入
			for(int x=0;x<name.length;x++) {
				raf.write(name[x].getBytes());
				raf.writeInt(age[x]);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

范例:使用RandomAccessFile读取数据

package com.lxh.sixteenchapter;

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

public class JavaIODemo422 {
    public static void main(String[] args) {
    	File file=new File("E:"+File.separator+"File"+File.separator+"ll.txt");
    	RandomAccessFile raf=null;
    	try {
			raf=new RandomAccessFile(file,"rw");
		
			{
		    	//读取王五的数据,跳过24位
			    raf.skipBytes(24);
			    byte data[]=new byte[8];
			    int len=raf.read(data);
			    System.out.println("姓名:"+new String(data,0,len).trim()+"年龄:"+raf.readInt());
			}
			
			{
				//读取李四的数据,回跳12位
			    raf.seek(12);
			    byte data[]=new byte[8];
			    int len=raf.read(data);
			    System.out.println("姓名:"+new String(data,0,len).trim()+"年龄:"+raf.readInt());
			}
			{
				//读取张三的数据,回跳到开始点
			    raf.seek(0);
		     	byte data[]=new byte[8];
		     	int len=raf.read(data);
		    	System.out.println("姓名:"+new String(data,0,len).trim()+"年龄:"+raf.readInt());
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(raf!=null) {
				try {
					raf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

执行结果

姓名:wangwu年龄:40
姓名:lisi年龄:23
姓名:zhangsan年龄:17
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值