public String name=null;
public int age=0;
public static final int LEN=8;
public Employee(String name,int age){
if(name.length()>LEN){
this.name=name.substring(1,LEN);
}
else{
while(name.length()<LEN){
this.name+="\0000";
}
}
this.name=name;
this.age=age;
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";
}
}
}
}
复制代码
作者: 李菁 时间: 2012-7-24 23:39
class Employee {
public String name=null;
public int age=0;
public static final int LEN=8;
public Employee(String name,int age){
if(name.length()>LEN){ 应该是this.name
this.name=name.substring(1,LEN);
}
else{
while(name.length()<LEN){ 也是this.name
this.name+="\0000";
}
}
this.name=name;
this.age=age;