Java Reference
In-Depth Information
dos.writeFloat(1.0F);
}
catch (IOException ioe)
{
System.err.println("i/o
error:
"+ioe.getMessage());
}
try (DataInputStream dis =
new
DataInputStream(new
FileIn-
putStream(FILENAME)))
{
System.out.println(dis.readInt());
System.out.println(dis.readUTF());
System.out.println(dis.readFloat());
}
catch (IOException ioe)
{
System.err.println("i/o
error:
"+ioe.getMessage());
}
}
}
DataStreamsDemo
creates a file named
values.dat
, calls
DataOut-
putStream
methodstowriteaninteger,astring,andafloating-pointvaluetothisfile,
and calls
DataInputStream
methods to read back these values. Unsurprisingly, it
generates the following output:
1995
Saving this String in modified UTF-8 format!
1.0
Caution
When reading a file of values written by a sequence of
DataOut-
putStream
method calls, make sure to use the same method-call sequence. Other-
wise,you'reboundtoendupwitherroneousdataand,inthecaseofthe
readUTF()
methods,throwninstancesofthe
java.io.UTFDataFormatException
class(a
subclass of
IOException
).