码迷,mamicode.com
首页 > 编程语言 > 详细

Java 保存对象到文件并恢复 ObjectOutputStream/ObjectInputStream

时间:2017-12-19 19:41:28      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:system   序列   tar   恢复   post   col   add   fileinput   new   

1.从inputFile文件中获取内容,读入到set对象;

2.然后通过ObjectOutputStream将该对象保存到outputFile文件中;

3.最后通过ObjectInputStream从outputFile文件中重新读出set对象。

    public static void objectWriteAndRead(String inputFile, String outputFile) {
        System.out.println("objectWriteAndRead ...");
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFile));
            String line = null;
            Set<String> hashSet = new HashSet<>();
            while (null != (line = bufferedReader.readLine())) {
                hashSet.add(line);
            }
            System.out.println("hashSet.size:" + hashSet.size());
            System.out.println(hashSet.toString());

            //write object
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(outputFile));
            objectOutputStream.writeObject(hashSet);
            objectOutputStream.close();

            //read object
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(outputFile));
            Set<String> objectRead = (Set<String>) objectInputStream.readObject();
            System.out.println("objectRead.getClass:" + objectRead.getClass());
            System.out.println("objectRead:\n" + objectRead.toString());

        } catch (Exception error) {
            error.printStackTrace();
        }
    }

 

参考:java对象序列化并存储到文件和数据库

Java 保存对象到文件并恢复 ObjectOutputStream/ObjectInputStream

标签:system   序列   tar   恢复   post   col   add   fileinput   new   

原文地址:http://www.cnblogs.com/bymo/p/8066812.html

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