码迷,mamicode.com
首页 > 其他好文 > 详细

写几个关于IO的回顾吧

时间:2015-03-16 01:02:30      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:javase   记录   io   

上午将开题报告写完了。下午的时候做了90道关于javaSE部分的题。晚上把Jdbc连接部分又回顾了一下。现在回顾一下IO的几个包装类吧。
ObjectInputStream/ObjectOutputStream

ObjectOutputStream oos = null;
try{
    oos = new ObjectOutputStream(new FileOutputStream(new File("person.bat")));

    oos.writeObject(new Person("zhangsan",23));
    oos.flush();
    oos.writeObject(new Person("lisi",12));
    oos.flush();
} catch(Exception e){
    System.out.println(e.getMessage());
} finally {
    if(oos != null){
        try{
            oos.close();
        } catch(){
        }
    }
}
try{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.bat"));

Person per1 = ois.readObject();
Person per2 = ois.readObject();

System.out.println("per1:" + per1 + " per2:" + per2);
} catch(Exception e){
    System.out.println(e.getMessage());
} finally {
    if(ois != null){
        try{
            ois.close();
        }catch(){

        }
    }
}
public class Person implements Serializable{
    private static final long serivalVersionUID = 1L;
    private String name;
    private int age;
    ......

}

这就完成了对象的序列化和反序列化

再来一个比较特殊的

RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try{
    raf1 = new RandomAccessFile(new File("a.txt"), "r");
    raf2 = new RandomAccessFile(new File("b.txt"), "rw");
    byte[] b = new byte[20];
    int len;
    while((len = raf1.read(b))!= -1){
        raf2.write(b, 0, len);
    }
} catch(){

}finally {
    if(raf1 != null){
        try{
            ra1.close();
        } catch (){

        }
        try{
            raf2.close();
        } catch (){

        }
    }
}

这样好像什么效果都没体现出来!!!!其实主要还是一个seek()方法的使用

再看看这个例子

@Test
    public void test(){
        RandomAccessFile rs1 = null;
        try {
            rs1 = new RandomAccessFile(new File("e.txt"), "rw");
            rs1.seek(4);
            StringBuffer sb = new StringBuffer(rs1.readLine());
            rs1.seek(4);
            rs1.write("xy".getBytes());
            rs1.write(sb.toString().getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(rs1 != null){
                try {
                    rs1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

写几个关于IO的回顾吧

标签:javase   记录   io   

原文地址:http://blog.csdn.net/sloverpeng/article/details/44285797

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!