|
Java > IO > Serialize object to file |
|
Serialize object to file
The following example shows how to serialize list of strings to a flat file.
|
package com.bethecoder.tutorials.io;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.List;
public class ObjectOutputStreamTest {
/**
* @param args
*/
public static void main(String[] args) {
try {
List<String> list = Arrays.asList(new String [] {
"ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX"
});
System.out.println("list : " + list);
ObjectOutputStream output =
new ObjectOutputStream(new FileOutputStream("C:\\example.ser"));
output.writeObject(list);
output.close();
System.out.println("Successfully written list to file");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
| |
It gives the following output,
list : [ONE, TWO, THREE, FOUR, FIVE, SIX]
Successfully written list to file
|
|