你的问题解决了,看注释。。- package test2;
- import java.io.RandomAccessFile;
- public class RandomFileTest {
- public static void main(String[] args) throws Exception {
- Employee e1 = new Employee("zhangsan", 23);
- Employee e2 = new Employee("lisi", 29);
- Employee e3 = new Employee("wangwu", 19);
- RandomAccessFile ra = new RandomAccessFile("src/employee.txt", "rw");
- ra.write(e1.name.getBytes());
- ra.write(e1.age);
- ra.write(e2.name.getBytes());
- ra.write(e2.age);
- ra.write(e3.name.getBytes());
- ra.write(e3.age);
- ra.close();
- int len = 0;
- byte[] buf = new byte[8];
- String strName = null;
- RandomAccessFile raf = new RandomAccessFile("src/employee.txt", "r");
- raf.skipBytes(12);
- len = raf.read(buf);
- strName = new String(buf, 0, len);
- System.out.println(strName + " : " + raf.read());
- raf.seek(0);
- len = raf.read(buf);
- strName = new String(buf, 0, len);
- System.out.println(strName + " : " + raf.read());
- raf.skipBytes(12);
- len = raf.read(buf);
- strName = new String(buf, 0, len);
- System.out.println(strName + " : " + raf.read());
- raf.close();
- }
- }
- class Employee {
- public String name = null;
- public int age = 0;
- public static final int LEN = 8;
- public Employee(String name, int age) {
- //首先,你要先为name,age赋值,再操作name
- this.name = name;
- this.age = age;
-
- //if和while的括号里要判断的是this.name,不是name,搞清楚了
- if (this.name.length() > LEN) {
- this.name = name.substring(0, LEN);
- } else {
- while (this.name.length() < LEN) {
- this.name += "\0000";
- }
- }
- }
- }
复制代码 |