JavaIO之RandomAccessFile(一)

package three.day.io;


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


public class RandomAccessFileTs {
public static void main(String[] args) throws IOException{
Person5 person51 = new Person5("zhangsan", 21);
Person5 person52 = new Person5("lisi", 22);
Person5 person53 = new Person5("wangwu", 23);
try {
RandomAccessFile file = new RandomAccessFile("RandomAccessFile.txt","rw");
file.write(person51.getName().getBytes());
file.writeInt(person51.getAge());
file.write(person52.getName().getBytes());
file.writeInt(person52.getAge());
file.write(person53.getName().getBytes());
file.writeInt(person53.getAge());
file.close();
RandomAccessFile file1 = new RandomAccessFile("RandomAccessFile.txt","r");
file1.skipBytes(12);
byte[] b = new byte[8];
file1.read(b, 0, b.length);
System.out.println(new String(b).trim());
System.out.println(file1.readInt());
file1.read(b, 0, b.length);
System.out.println(new String(b).trim());
System.out.println(file1.readInt());
file1.seek(0);
file1.read(b, 0, b.length);
System.out.println(new String(b).trim());
System.out.println(file1.readInt());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
class Person5 {
private String name;
private int age;
private static final int NAME_LEN = 8;
public Person5(String name, int age) {
super();
if(name.length()>NAME_LEN)
this.name = name.substring(0, 8);
else{
this.name = name;
for(int i=0;i<NAME_LEN - name.length();i++){
this.name = this.name + "\0";
}
}
System.out.println(name.length() + " " + this.name.length());
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static int getNameLen() {
return NAME_LEN;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值