Java Reference
In-Depth Information
public class ReadingPrimitives {
public static void main(String[] args) {
String srcFile = "primitives.dat";
try (DataInputStream dis = new DataInputStream(
new FileInputStream(srcFile))) {
// Read the data in the same order they were written
int intValue = dis.readInt();
double doubleValue = dis.readDouble();
boolean booleanValue = dis.readBoolean();
String msg = dis.readUTF();
System.out.println(intValue);
System.out.println(doubleValue);
System.out.println(booleanValue);
System.out.println(msg);
}
catch (FileNotFoundException e) {
FileUtil.printFileNotFoundMsg(srcFile);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
765
6789.5
true
Java Input/Output is cool!
Object Serialization
You create an object using the
new
operator. For example, if you have a
Person
class that accepts a person's name,
gender, and height as arguments in its constructor, you can create a
Person
object as follows:
Person john = new Person("John", "Male", 6.7);
What would you do if you wanted to save the object
john
to a file and later restore it in memory without using the
new
operator again? You have not learned how to do it yet. This is the subject of the discussion in this section.
The process of converting an object in memory to a sequence of bytes and storing the sequence of bytes in a
storage medium such as a file is called
object serialization
. You can store the sequence of bytes to permanent storage
such as a file or a database. You can also transmit the sequence of bytes over a network. The process of reading
the sequence of bytes produced by a serialization process and restoring the object back in memory is called
object
deserialization
. The serialization of an object is also known as
deflating
or
marshalling
the object. The deserialization
of an object is also known as
inflating
or
unmarshalling
the object. You can think of serialization as writing an object
from memory to a storage medium and deserialization as reading an object into memory from a storage medium.