Java基础之序列化对象——反序列化对象(DeserializeObjects)

控制台程序,使用如下代码能读入包含Junk对象的文件:

 1 import java.io.*;
 2 import java.nio.file.*;
 3 
 4 class DeserializeObjects {
 5   public static void main(String args[]) {
 6     Path file = Paths.get(System.getProperty("user.home")).resolve("Beginning Java Struff").resolve("JunkObjects.bin");
 7     if(Files.notExists(file)) {
 8       System.out.printf("
File %s does not exist.", file);
 9       System.exit(1);
10     }
11 
12     int objectCount = 0;                                               // Number of objects read
13     try (ObjectInputStream objectIn = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(file)))){
14        // Read from the stream until we hit the end
15        Junk object = null;                                             // Stores an object reference
16        while(true) {
17         object = (Junk)objectIn.readObject();                          // Read an object
18         ++objectCount;                                                 // Increment the count
19         System.out.println(object);                                    // Output the object
20       }
21 
22     } catch(EOFException e) {                                          // This will execute when we reach EOF
23       System.out.println("EOF reached. "+ objectCount + " objects read.");
24 
25     } catch(IOException|ClassNotFoundException e) {
26       e.printStackTrace();
27     }
28   }
29 }
原文地址:https://www.cnblogs.com/mannixiang/p/3409400.html