package com.geminno.he0228;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;
public class RandomAccessFileDemo {
public static void main(String[] args) throws IOException{
//
Person[] persons = { new Person("chenhao", 30),
new Person("zhangsan", 50), new Person("lisi", 25),
new Person("wangwu", 18) };
RandomAccessFile randomAccessFile = new RandomAccessFile("d:\\io2.txt", "rw");
//写入数据到randomAccessFile对象中
for (int i = 0; i < persons.length; i++) {
randomAccessFile.writeChars(persons[i].getName());
randomAccessFile.writeInt(persons[i].getAge());
}
//读取指定位置上的Person对象
Scanner scanner=new Scanner(System.in);
System.out.println("读取第几个Person对象:");
int num=scanner.nextInt();
// 使用seek方法来操作存储位置
randomAccessFile.seek((num-1)*Person.size());
Person person=new Person();
person.setName(readName(randomAccessFile));
person.setAge(randomAccessFile.readInt());
System.out.println("姓名:"+person.getName());
System.out.println("年龄:"+person.getAge());
randomAccessFile.close();
}
public static String readName(RandomAccessFile randomAccessFile) throws IOException{
char []name=new char[15];
for (int i = 0; i < name.length; i++) {
name[i]=randomAccessFile.readChar();
}
return new String(name).replace('\u0000',' ');
}
}
class Person {
private String name;
private int age;
// 创建一个无参的构造方法
public Person() {
}
// 带有两个参数的构造方法
public Person(String name, int age) {
// 创建一个动态字符串
StringBuilder stringBuilder = null;
if (name != null) {
// StringBuilder的默认大小为str.length() + 16,字符串长度+16个
stringBuilder = new StringBuilder(name);
} else {
stringBuilder = new StringBuilder(15);// 自定义长度为15的字符串
}
stringBuilder.setLength(15);// 固定长度为15个,占用了30个字节的大小,如果长度不满15个,那么后面就会以空字符"\u0000"来表示
this.name = stringBuilder.toString();
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
// 创建一个动态字符串
StringBuilder stringBuilder = null;
if (name != null) {
// StringBuilder的默认大小为str.length() + 16,字符串长度+16个
stringBuilder = new StringBuilder(name);
} else {
stringBuilder = new StringBuilder(15);// 自定义长度为15的字符串
}
stringBuilder.setLength(15);// 固定长度为15个,占用了30个字节的大小,如果长度不满15个,那么后面就会以空字符"\u0000"来表示
this.name = stringBuilder.toString();
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static int size() {
return 34;
}
}
转载于:https://my.oschina.net/YongfengHe/blog/625457