Question

How can I write primitive data-types to disk? In C/C++, the printf statement could write integers, floats, as well as other types.

Answer

Writing primitive data-types can be easily done, using the DataOutputStream class. DataOutputStream provides simple methods to write primitive data-types out to any output stream, whether it be the user console, a network connection, or a file.

Data Type

Method

boolean writeBoolean(boolean v);
byte writeByte(int v);
writeBytes(String s);
char, string writeChar(int v);
writeChars(String s);
double writeDouble(double v);
float writeFloat(float v);
int writeInt(int v);
long writeLong(long v);
short writeShort(int v);
string writeUTF(String str);

Figure 1.0 - Methods of DataOutputStream

Java also provides a corresponding DataInputStream, which will allow you to read data back. This means you can write a data structure out to a disk or network connection, and read it back at a later date.


Back