?java——名称显示错误问题

2019年2月22日00:27:25 发表评论 1,226 views
import java.io.*;
import java.io.RandomAccessFile;
public class nametxt {
    //复杂问题,第一:员工2年龄显示问题,2 补全空格出现零的问题/

    public static void main(String[] args)
            throws Exception//为什么设置这???
    {
        // TODO 自动生成的方法存根
        Employee e1 = new Employee("zhangsan",23);
//    Employee e2 = new Employee("lisi",224);
        Employee e2 = new Employee("lisi",24);
        Employee e3 = new Employee("wangwu",25);
        RandomAccessFile ra = new RandomAccessFile("c:\\employee.txt","rw");
        ra.write(e1.name.getBytes());
        ra.writeInt(e1.age);
        ra.write(e2.name.getBytes());
        ra.write(e2.age);
        ra.write(e3.name.getBytes());
        ra.write(e3.age);
        ra.close();
        RandomAccessFile raf=new RandomAccessFile("c:\\employee.txt","r");
        int len = 8;
        raf.skipBytes(12);//跳过第一个员工的信息,其姓名8字节,年龄4字节
        System.out.println("第2个员工信息:");
        String str = "";
        for(int i=0;i<len;i++)
            str = str+(char)raf.readByte();
        System.out.println("name:"+str);
        System.out.println("age:"+raf.readInt());
        System.out.println("第1个员工的信息:");
        raf.seek(0);//将文件指针移到文件开始位置
        str = "";
        for(int i = 0 ;i<len;i++)
            str = str+(char)raf.readByte();
        System.out.println("name:"+str);
        System.out.println("age:"+raf.readInt());
        System.out.println("第三个员工的信息:");
        raf.skipBytes(12);
        str = "";
        for(int i = 0;i<len;i++)
            str = str+(char)raf.readByte();
        System.out.println("name:"+str.trim());
        System.out.println("age:"+raf.readInt());
        raf.close();

    }

}
class Employee
{
    String name;
    int age;
    final static int LEN = 8;
    public Employee(String name,int age)
    {
        if(name.length()>LEN)
            name = name.substring(0,8);
        else{
            while(name.length()<LEN){
                name = name+"\u0000";
//       System.out.println(name);
            }

        }
        this.name = name;
        this.age = age;

    }
}



结果:
第2个员工信息:
name:lisi
ge:410476910
第1个员工的信息:
name:zhangsan
age:23
第三个员工的信息:
name:gwu


发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: