这是源代码:
import java.io.RandomAccessFile;
/**记录3个员工的文本,用RandomAccessFile进行操作
* 听说要求是每个字段都要相同的长
*
*/
class Employee
{
private String name;
private int age;
public static final int LEN=14;
public Employee()
{
}
public Employee(String name,int age)
{
if(name.length()>LEN)
{
name=name.substring(0,LEN);
}
else
while(name.length()<LEN)
{
name+="\u0000";
}
this.name=name;
this.age=age;
}
//method: getName(),getAge()
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class RandomAccessFileTest {
public static void main(String[] args) throws Exception
{
Employee e1=new Employee("zhaobo",21);
Employee e2=new Employee("zhaoyunxia",20);
Employee e3=new Employee("baby",2);
RandomAccessFile raf =new RandomAccessFile("employee.txt", "rw");
raf.writeChars(e1.getName());
raf.writeInt(e1.getAge());
raf.writeChars(e2.getName());
raf.writeInt(e2.getAge());
raf.writeChars(e3.getName());
raf.writeInt(e3.getAge());
raf.close();
RandomAccessFile raf2 =new RandomAccessFile("employee.txt", "r");
byte[] buf=new byte[Employee.LEN];//长度为14字节的缓冲区
int buflen;//读入缓冲区的字节数
String strName="";
//int iage;
//no.2
raf2.seek(Employee.LEN+4);
buflen=raf2.read(buf);
strName=new String(buf,0,buflen);
//System.out.println("buflen :"+buflen);
//iage=raf2.readInt();
System.out.println(strName+";"+raf2.readInt());
//no.1
raf2.seek(0);
buflen=raf2.read(buf);
strName=new String(buf,0,buflen);
//iage=raf2.readInt();
System.out.println(strName+";"+raf2.readInt());
//no.3
raf2.skipBytes(Employee.LEN+4);
buflen=raf2.read(buf);
strName=new String(buf,0,buflen);
//iage=raf2.readInt();
System.out.println(strName+";"+raf2.readInt());
raf2.close();
}
}
我本以为的运行结果是
zhaoyunxia :20
zhaobo :21
baby :2
但实际结果却是:
:7995496
z h a o b o :0
a o x u n x i:6356992
对了,我用的是eclipse,我用dos运行直接给我抛出一堆异常了......
我调试了一下,发现错在
strName=new String(buf,0,buflen);
执行到这句,strName没有正确的接收到名字。
但是不知道为什么
[此贴子已经被作者于2007-4-21 19:02:28编辑过]