DataInputStream Class
Package: java.io
This class reads primitive data types, such as integers and doubles, directly from an input stream. It is the class you’ll use most often to read data from a binary file.
Constructor
Constructor |
Description |
|
Creates a data input stream from any object that extends the |
Methods
Method |
Description |
|
Reads a |
|
Reads a |
|
Reads a |
|
Reads a |
|
Reads a |
|
Reads an |
|
Reads a |
|
Reads a |
|
Reads a string stored in UTF format from the input stream. It throws |
Creating a DataInputStream
To read data from a binary file, you want to connect a DataInputStream
object to an input file. To do that, you use a File
object to represent the file, a FileInputStream
object that represents the file as an input stream, a BufferedInputStream
object that adds buffering to the mix, and finally a DataInputStream
object to provide the methods that read various data types. Here’s an example:
File file;
FileInputStream fstream;
BufferedInputStream bstream;
DataInputStream in;
file = new File(“movies.dat”);
fstream = new FileInputStream(file);
bstream = new BufferedInputStream(fs);
in = new DataInputStream(bs);
Reading from a data input stream
To read data from a binary file, you use the various read
methods of the DataInputStream
class to read the fields one at a time. Of course, to do that, you must know the exact sequence in which data values appear in the file.
Suppose a file includes information from a video store rental database that represents the title of a movie as a string, the year the movie was made as an integer, and the movie’s rental price as a double, in that order. To read these three values, you’d use these statements:
String title = in.readUTF();
int year = in.readInt();
double price = in.readDouble();
The read
methods usually are used in a while
loop to read all the data from the file. When the end of the file is reached, EOFException
is thrown. Then you can catch this exception and stop the loop. For example:
boolean eof = false;
while (!eof)
{
try
{
String title = in.readUTF();
int year = in.readInt();
double price = in.readDouble();
// do something with the data here
}
catch (EOFException e)
{
eof = true;
}
catch (IOException e)
{
System.out.println(“An I/O error “
+ “has occurred!”);
System.exit(0);
}
}
Here, the boolean
variable eof
is set to true
when EOFException
is thrown, and the loop continues to execute as long as eof
is false
.
in.close();
This method also throws IOException
, so you want to place it inside a try/catch
block. (See try Statement in Part 2 for more information.)