Java IO-RandomAccessFile

RandomAccessFile主要功能是随机读取,可以读取指定位置的内容,可以跳过指定的字节数读取

package com.zzh.io;

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

public class RandomAccessFileDemo {

/**
* RandomAccessFile主要功能是随机读取,可以读取指定位置的内容,可以跳过指定的字节数读取
*/
public static void main(String[] args) throws IOException {
testWrite();
testRead();
}

private static void testWrite() throws IOException {
File file = new File("D:" + File.separator + "test.txt");
//RandomAccessFile的构造函数的第1个参数表示文件,
//第2个参数表示文件打开的模式,常用有3种:r,w,rw
//rw:如果文件不存在,会自动创建
RandomAccessFile raf = new RandomAccessFile(file, "rw");

String name = null;
int age = 0;

name = "zhangsan";
age = 18;
raf.writeBytes(name);
raf.writeInt(age);

name = "lisi ";//这里要补全空格,使字符串为8位,否则读取时会出错
age = 19;
raf.writeBytes(name);
raf.writeInt(age);

name = "wangwu ";//这里要补全空格,使字符串为8位,否则读取时会出错
age = 20;
raf.writeBytes(name);
raf.writeInt(age);

raf.close();//关闭资源文件,切记!
}

private static void testRead() throws IOException {
File file = new File("D:" + File.separator + "test.txt");
RandomAccessFile raf = new RandomAccessFile(file, "r");

String name = null;
int age = 0;
byte[] b = new byte[8];

raf.skipBytes(12);//跳过第一个人的12个字节,读第二个人的信息
for (int i = 0; i < b.length; i++) {
b[i] = raf.readByte();//读取一个字节
}
name = new String(b);
age = raf.readInt();
System.out.println("第二个人的姓名:" + name + ", 年龄:" + age);

raf.seek(0);//将指针定位回文件开始处,读第一个人的信息
for (int i = 0; i < b.length; i++) {
b[i] = raf.readByte();//读取一个字节
}
name = new String(b);
age = raf.readInt();
System.out.println("第一个人的姓名:" + name + ", 年龄:" + age);

raf.seek(24);//将指针定位到第三个人处,读第三个人的信息
// raf.skipBytes(12);//空出第二个人的信息,读第三个人的信息
for (int i = 0; i < b.length; i++) {
b[i] = raf.readByte();//读取一个字节
}
name = new String(b);
age = raf.readInt();
System.out.println("第三个人的姓名:" + name + ", 年龄:" + age);

raf.close();//关闭资源文件,切记!
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值