package demo;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileDemo {
public static void main(String[] args) throws IOException {
writeFile();
readFile();
readFile_2();
}
public static void writeFile() throws IOException {
RandomAccessFile raf = new RandomAccessFile("ranacc.txt","rw");
raf.write("张三".getBytes());
raf.writeInt(97);
raf.write("小强".getBytes());
raf.writeInt(99);
raf.close();
/*
* 在当前目录下新建ranacc.txt文件,其内容为:张三 a小强 c
* 大小为:16字节(一个汉字2字节,writeInt强制写入4字节,97占1字节,前面补0或空格)
*/
}
public static void readFile() throws IOException {
RandomAccessFile raf = new RandomAccessFile("ranacc.txt", "rw");
byte[] buf = new byte[4];//因为一个中文2字节,张三占4个字节,这里先读取姓名
raf.read(buf);
String name = new String(buf);
System.out.println(name);//输出张三
int age = raf.readInt();
System.out.println(age);//输出97
//通过getFilePointer()方法获取指针当前位置
System.out.println(raf.getFilePointer());//输出8,说明当前指针在数组第8个元素的位置,前面0~7正好8个字节,存放张三97
raf.close();
}
/*
* RandomAccessFile读和写的图解见桌面:
* (1)数组一个元素表示1个字节;
* (2)一个汉字=2个字节,图中一个框中存一半汉字,2个框存一个汉字;
* (3)97占1个字节,由于writeInt()方法写入的97,所以强制凑齐4个字节,那么前面补3个0,然后存入97(99同理);
* (4)自定义函数readFile()先用RandomAccessFile类特有方法read()读取数组中0~3角标对应的4个元素存入buf,之后buf转为
* String,从而name=张三,输出张三;再用RandomAccessFile类特有方法readInt()读取4~7角标对应的4个元素,转为int,输出97
*
* 此时指针停在8位置,52行代码验证了这一点。
*/
public static void readFile_2() throws IOException {
/*
* 【需求】直接读取第二个人的信息
* 那么就用seek()方法设置指针初始位置8,之后用同样的方法读取
*/
RandomAccessFile raf = new RandomAccessFile("ranacc.txt","rw");
raf.seek(1*8);//随机读取,通过指定指针位置来完成。(想读什么信息就读什么信息),1*8是第一个人,姓名+年龄占8字节
byte[] buf = new byte[4];
raf.read(buf);
String name = new String(buf);
System.out.println(name);//输出小强
int age = raf.readInt();
System.out.println(age);//输出99
raf.close();
}
}
24-IO流-60-IO流(RandomAccessFile-读取&随机读取)
最新推荐文章于 2022-05-08 22:54:02 发布