JAVA的IO操作(二)

来源:互联网 发布:最好企业网络投资理财 编辑:程序博客网 时间:2024/04/30 14:22

上一讲介绍了File类的常见操作,接下来介绍文件内容的操作,即: RandomAccessFile类的使用。RandomAccessFile实现了文件的随机读取的功能
一:写入操作:

File f=new File("e:"+File.separator+"test.txt");//传路径需要这一层的包装        RandomAccessFile ref=null;        ref=new RandomAccessFile(f, "rw");              //读写模式文件不存在自动创建        String name=null;        int age=0;        name="zhangsan";                                //字符串的长度为8        age=30;                                         //数字的长度为4        ref.writeBytes(name);        ref.writeInt(age);        name="lisi    ";        age=31;                                                 ref.writeBytes(name);        ref.writeInt(age);        name="wangwu  ";        age=32;                                                 ref.writeBytes(name);        ref.writeInt(age);        ref.close();                                    //注意关闭

二:读取的操作:

File f=new File("e:"+File.separator+"test.txt");//传路径需要这一层的包装        RandomAccessFile ref=null;        ref=new RandomAccessFile(f, "r");               //以只读的方式打开文件        String name=null;        int age=0;        //一般的向程序中读取数据,代码的逻辑是模板        byte[] b=new byte[8];                           //开辟byte数组        ref.skipBytes(12);                              //跳过第一个人的信息        for (int i = 0; i < b.length; i++) {            b[i]=ref.readByte();                        //每次读取一个字节        }        name=new String(b);                                     age=ref.readInt();        System.out.println("第二个人的信息:姓名:"+name+",年龄:"+age);        ref.close();

RandomAccessFile类有个静态方法seek(),此方法能够设置文件中的指针,设置从哪一个地方开始读取或者写入

0 0