Java 核心技术(第八版)卷II:高级知识:例1-2P25RandomFileTest

本例子演示读写二进制数据,使用DataOutput接口:DataOutputStream类实现了DataOutput接口使用了DataInput接口:DataInputStream类实现了DataInput接口。RandomAccessFile类可以在文件中的任何位置查找或者写入数据。

import java.util.Date;
import java.util.GregorianCalendar;
import java.io.*;
import java.util.*;
public class RandomFileTest {
    public static void main(String[] args)
    {
        Employee[] staff=new Employee[3];
        staff[0]= new Employee("Carl Cracker",75000,1987,12,15);
        staff[1]= new Employee("Harry Hacker",50000,1989,10,1);
        staff[2]= new Employee("Tony Tester",40000,1990,3,15);
        try
        {
            //save all employee records to the file employee.dat
            DataOutputStream out=new DataOutputStream(new FileOutputStream("employee.dat"));
            System.out.println("I will print the staff array:");
            for(Employee e:staff)
                e.writeData(out);
            out.close();

            //retrieve all records into a new array
            RandomAccessFile in=new RandomAccessFile("employee.dat","r");
            //计算数组的尺寸
            int n=(int)(in.length()/Employee.RECORD_SIZE);
            Employee[] newStaff=new Employee[n];
            //read employees in reverse order
            for(int i=n-1;i>=0;i--)
            {
                newStaff[i]=new Employee();
                in.seek(i*Employee.RECORD_SIZE);//Sets the file-pointer offset, measured from the beginning
                                                    // of this file, at which the next read or write occurs
                newStaff[i].readData(in);
            }
            in.close();
            //print the newly read employee records
            for(Employee e:newStaff)
                System.out.println(e);
        }
        catch (IOException exception)
        {
            exception.printStackTrace();//Prints this throwable and its backtrace to the standard error stream.
        }

    }
}
class Employee
{
    public Employee() { }
    public Employee(String n,double s,int year,int month,int day)
    {
        name=n;
        salary=s;
        GregorianCalendar calendar=new GregorianCalendar(year,month-1,day);
        hireDay=calendar.getTime();
    }
    public String getName()
    {
        return name;
    }
    public double getSalary()
    {
        return  salary;
    }
    public Date getHireDay()
    {
        return hireDay;
    }
    public void raiseSalary(double byPercent)
    {
        double raise=salary*byPercent/100;
        salary+=raise;
    }
    public String toString()
    {
        return getClass().getName()+"[name="+name+",salaray="+salary+",hireDay="+hireDay+"]";
    }
    //write employee data to a data output :code changed than before
    public void writeData(DataOutput out) throws IOException
    {
        DataIO.writeFixedString(name,NAME_SIZE,out);
        out.writeDouble(salary);

        GregorianCalendar calendar=new GregorianCalendar();
        calendar.setTime(hireDay);
        out.writeInt(calendar.get(Calendar.YEAR));
        out.writeInt(calendar.get(Calendar.MONTH)+1);
        out.writeInt(calendar.get(Calendar.DAY_OF_MONTH));
    }

    //Reads employee data from a data input
    public void readData(DataInput in) throws IOException
    {
        name=DataIO.readFixedString(NAME_SIZE,in);
        salary=in.readDouble();
        int y=in.readInt();
        int m=in.readInt();
        int d=in.readInt();
        GregorianCalendar calendar=new GregorianCalendar(y,m-1,d);
        hireDay=calendar.getTime();
    }
    public static final int NAME_SIZE=40;
    public static final int RECORD_SIZE=2*NAME_SIZE+8+4+4+4;
    private String name;
    private double salary;
    private Date hireDay;
}
class DataIO
{
    public static String readFixedString(int size,DataInput in) throws IOException
    {
        StringBuilder b=new StringBuilder(size);
        int i=0;
        boolean more=true;
        while(more&&i<size)
        {
            char ch=in.readChar();
            i++;
            if(ch==0) more=false;
            else b.append(ch);// b is a StringBuilder
        }
        in.skipBytes(2*(size-i));
        return b.toString();
    }
    public static void writeFixedString(String s,int size,DataOutput out) throws IOException
    {
        for(int i=0;i<size;i++)
        {
            char ch=0;
            if(i<s.length()) ch=s.charAt(i);
            out.writeChar(ch);
        }

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值