JavaIO之RandomAccessFile随机访问文件

package test.java.io;



import java.io.RandomAccessFile;



public class RandomAccFile {

    

    public static void main(String[] args) throws Exception {

        Employee emp1=new Employee("zhangsan",280);

        Employee emp2=new Employee("李四",18);

        Employee emp3=new Employee("tom",22);

        

        //表示该文件可读可写

        RandomAccessFile rdf=new RandomAccessFile("employment.txt","rw"); 

        //rdf.write(emp1.name.getBytes()); //write方法只能作用于英文,对中文

        rdf.writeChars(emp1.name); //在java中不管是英文字符还是中文字符都占有2个字节,它向文件中写入的是字符  16字节

        rdf.writeInt(emp1.age); //写进去的是4个字节,write写的是一个字节 4个字节

        

        rdf.writeChars(emp2.name);

        rdf.writeInt(emp2.age);

        

        //writeChars写入的每个字符占有2个字节

        rdf.writeChars(emp3.name);

        rdf.writeInt(emp3.age);

        

        rdf.close(); //关闭

        

        String strName="";

        //表示文件只能读

        RandomAccessFile readdf=new RandomAccessFile("employment.txt","r"); 

        

        //读李四的内容,跳过20个字节

        readdf.skipBytes(Employee.LEN*2+4);

        //for循环是根据字符来读取的,因此它不用乘以2

        for(int i=0; i<Employee.LEN;i++ )

        {

            strName+=readdf.readChar();//每次只读一个字符

        }

        //byte[] buf = new byte[Employee.LEN*2+4];

        //int len=0;

        //len= readdf.read(buf,0,Employee.LEN);

        //将字节数组转换成字符串

        //String strName=new String(buf,0,Employee.LEN);

        //readdf.read()读取得是一个字节,一旦年龄大于256,就会显示当前值减去256的结果

        //System.out.println(strName+":"+readdf.read());

        System.out.println(strName+": "+readdf.readInt());//readInt获取的是2个字节

    

        //读张三的内容

        strName="";

        readdf.seek(0);

        for(int i=0; i<Employee.LEN;i++ )

        {

            strName+=readdf.readChar();//每次只读一个字符

        }

        System.out.println(strName+": "+readdf.readInt());

        

        //读取tom的数据

        strName="";

        readdf.skipBytes(Employee.LEN*2+4);

        for(int i=0; i<Employee.LEN;i++ )

        {

            strName+=readdf.readChar();//每次只读一个字符

        }

        System.out.println(strName+": "+readdf.readInt());

    }    

} 
View Code

 

package test.java.io;



public class Employee {

    public String name=null;

    public int age=0;

    public final static int LEN=8;

    public Employee(String name,int age)

    {

        if(name.length()>LEN)

        {

            name=name.substring(0,LEN);

        }

        else

        {

            while(name.length()<8)

            {

                name+='\u0000';//空格李四

            }

        }

        this.name=name;

        this.age=age;

        

    }

        

}

 

你可能感兴趣的:(JavaIO之RandomAccessFile随机访问文件)