try { FileInputStream fileIn = new FileInputStream("data.txt"); ObjectInputStream in = new ObjectInputStream(fileIn); Object obj = in.readObject(); // do something with the object in.close(); fileIn.close(); } catch(IOException e) { e.printStackTrace(); } catch(ClassNotFoundException e) { e.printStackTrace(); }
try { Socket socket = new Socket("localhost", PORT); ObjectInputStream in = new ObjectInputStream(socket.getInputStream()); Object obj = in.readObject(); // do something with the object in.close(); socket.close(); } catch(IOException e) { e.printStackTrace(); } catch(ClassNotFoundException e) { e.printStackTrace(); }In this example, we create a Socket object to connect to a server running on the localhost on the specified PORT. Then, we create an ObjectInputStream object by calling the getInputStream() method of the Socket object. Finally, we read an object from the stream using the readObject() method of the ObjectInputStream class. We catch any IOException or ClassNotFoundException that might occur during this process. Both examples use classes from the java.io package, specifically the FileInputStream and ObjectInputStream classes.