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

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对象序列化并存储到文件和数据库

posted @ 2017-12-19 17:21  焦距  阅读(712)  评论(0编辑  收藏  举报