Java Reference
In-Depth Information
1.
Create a class called ObjectOutputStreamTest with the following contents:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class ObjectOutputStreamTest {
public static void main(String[] args) {
int number1 = 5;
double number2 = 10.3;
String string = "a string";
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
try (
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("saved.txt"));
) {
out.writeInt(number1);
out.writeDouble(number2);
out.writeBytes(string);
out.writeObject(list);
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.
Execute the program and refresh your Eclipse project. A file called saved.txt should appear with
contents similar to these:
@$™™™™™ša string¬í sr FileCopier$1ÍÉJ;¹-
\--------------------------------------------------------------------------------
xr java.util.ArrayListxÒ&traed;Ça•---------------------------------
I ----------------------------------------------------------------------------------
sizexpw-------------------------------------------------------------------------------
t at bx¬í w @$™™™™™ša stringsr FileCopier$1ÍÉJ;¹
\--------------------------------------------------------------------------------
xr java.util.ArrayListxÒ™Ça-------------------------------------- I
-------------------------------------------------------------------------------
sizexpw-------------------------------------------------------------------------------
t at bx
How It Works
Here's how it works:
1.
The ObjectOutputStream class is created as a wrapper around a normal FileOutputStream .
2.
Next, ObjectOutputStream exposes a number of methods, i.e. writeInt , writeDouble , and so
on, to write data to the stream.
Search WWH ::




Custom Search