In this example we will show how to write an object to file in Java.
Source Code
package com.beginner.examples;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class WriteObjctToFile2 {
public static void main(String[] args) {
try {
HashMap map = new HashMap();
map.put("name", "foolfish");
List list = new ArrayList();
list.add("hello");
list.add("everyone");
FileOutputStream outStream = new FileOutputStream("E:tmpTest.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outStream);
objectOutputStream.writeObject(map);
objectOutputStream.writeObject(list);
outStream.close();
System.out.println("successful");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
successful
References
Imported packages in Java documentation: