In this example we will show the method to read an object from file in Java.
Source Code
package com.beginner.examples;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.HashMap;
public class ReadObjectFromFile {
public static void main(String[] args) {
FileInputStream freader;
try {
freader = new FileInputStream("E:tmpTest.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(freader);
HashMap map = new HashMap();
map = (HashMap) objectInputStream.readObject();
System.out.println("The name is " + map.get("name"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Output:
The name is Alic
References
Imported packages in Java documentation: