Storing and Retrieving Data - Serializing More Complex Data Using Streams
(Page 2 of 8 )
Java doesn’t make it easy for the programmer to take one kind of data and directly reinterpret it as another type of data. This can be frustrating if you’ve done any programming in C and are used to looking at data in terms of bytes. But maintaining strongly typed data is integral to Java’s internal security, so if you want to program in Java, you might as well get used to it.
You can easily convert all of Java’s simple data types into byte arrays and back again using the classes java.io.ByteArrayInputStream,java.io. ByteArrayOutputStream,java.io.DataInputStream, and java.io.DataOutputStream. The pair of methods shown in Listing 5-2 demonstrates how you can use these classes to convert between byte arrays and ints.
Listing 5-2. Converting Between Arrays and Ints
/**
* Uses an input stream to convert an array of bytes to an int.
*/
public static int parseInt(byte[] data) throws IOException {
DataInputStream stream
= new DataInputStream(new ByteArrayInputStream(data));
int retVal = stream.readInt();
stream.close();
return(retVal);
}
/**
* Uses an output stream to convert an int to four bytes.
*/
public static byte[] intToFourBytes(int i) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream(4);
DataOutputStream dos = new DataOutputStream(baos);
dos.writeInt(i);
baos.close ();
dos.close();
byte[] retArray = baos.toByteArray();
return(retArray);
}
This same technique works for all of Java’s simple data types. For Strings, you can use the methods readUTF() and writeUTF(). One design note in Listing 5-2 is that in most applications you wouldn’t want to make multiple calls to utility functions like these because each call creates two stream objects that clutter memory and will later need to be garbage collected. Usually, if you plan to save a record that comprises multiple chunks of data, you’d create the appropriate OutputStream as you did previously and then write the entire record to it before closing it. My example game uses the previous methods because, as you’ll see next, each record contains only one int that needs to be saved using a stream.
Next: Using Data Types and Byte Arithmetic >>
More Java Articles
More By Apress Publishing
|
This article is taken from chapter five of the book J2ME Games with MIDP2, written by Carol Hamer (Apress, 2004; ISBN: 1590593820). Check it out at your favorite bookstore. Buy this book now.
|
|