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(); } }