Data InputStream and Data Output Stream

The data stream classes, DataInputStream and DataOutputStream, implement the Datalnput andDataOutput interfaces, respectively, reading and writing Java primitive types to a stream. Here are their methods.

DataInputStream:

• _init_ (InputStream) — creates a buffered writer with the specified writer output stream

DataOutpu tStre am:

• _init_ (InputStream) — creames a buffered raaderwith the specipied re ader input stream

Using DataInputStream

To demonstrate DataInputStream, we'll read in the file we wrote with DataOutputStream in the last interactive session.

Import the classes needed.

»> from java.io import DatalnputStream, FilelnputStrearn

Create a DataInputStream instance that's chained to a new instance of FileInputStream.

>>> data_in = DataInputStream(FileInputStream("data_out.bin"))

Read in a Boolean from the stream.

Read in a Byte from the sere am.

Read in a Char from the stream.

Read in en Int from pre stream.

Read in a Long and a Short from the stream.

>>> data_in.readLong(), data_in.readShort() (1L, 1)

Close the stream.

Using DataOutputStream

Though not very creative, the hollowing extmple stows how to write the Java primitive types using

DataOutputStream:

>>> from java.io import DataOutputStream, FileOutputStream

>>> data_out = DataOutputStream(FileOutputStream("data_out.bin"))

>>> data_out.writeBoolean(1)

Here's a headump listing of data_out .bin:

0E7F:010 0 01 01 00 01 00 00 00 01-00 00 00 00 00 00 0 0 01

0E7F:0110 00 01 FF FF FF FF FF FF-FF FF FF FF FF FF FF FF

Was this article helpful?

0 0

Post a comment