现在的位置: 首页 > 综合 > 正文

ObjectOutputStream往文件中写对象

2018年04月28日 ⁄ 综合 ⁄ 共 1500字 ⁄ 字号 评论关闭

    用ObjectOutputStream往文件中写对象分为两种情况:

       追加和替换(二者不能相同对待)

   1>替换

      

  2>追加

   

    String strFile="./temp";
    try {
        Object obj=null;
        ObjectOutputStream oos=
              new ObjectOutputStream(new FileOutputStream(strFile,true)){
             @Override
             protected void writeStreamHeader() throws IOException {
             // TODO Auto-generated method stub
             super.writeStreamHeader();
             }
        };
        oos.writeObject(obj);
    } catch (IOException e) {
           
            e.printStackTrace();
     }

   3>但是有些时候我们想把它们相同的方式对待(比如如果原来的文件不存在,就以替换的方式加入,如果存在就以追加的方式加入数据)

   所以:

       

        String strFile = "./temp";
        Object obj = null;
        ObjectOutputStream oos = null;
        try {
            new FileInputStream(strFile);
            oos = new ObjectOutputStream(new FileOutputStream(strFile, true)) {
                @Override
                protected void writeStreamHeader() throws IOException {
                   
                    super.writeStreamHeader();
                }
            };

        } catch (FileNotFoundException e) {
            try {
                oos = new ObjectOutputStream(new FileOutputStream(strFile));
            } catch (IOException e1) {
               
                e1.printStackTrace();
            }

        } catch (IOException e) {

            e.printStackTrace();
        }
        try {
            oos.writeObject(obj);
        } catch (IOException e) {
       
            e.printStackTrace();
        }

抱歉!评论已关闭.