The ReadBinFile example reads the file File1.dat, produced by WriteBinFile described, and prints the file contents.
ReadBinFile
import java.io.*;
public class ReadBinFile
{
public static void main(String[] args) throws
IOException
{
float price;
int qty;
char singlechar;
StringBuffer item;
FileInputStream fileIn = new FileInputStream(''File1.dat");
DataInputStream in = new DataInputStream(fileIn);
try
{
while (true)
{
item = new StringBuffer(30);
while ((singlechar = in.readChar()) != ';')
{
item.append(singlechar);
}
Price = in.readFloat();
in.readChar(); /* skip field separator */
qty = in.readInt();
in.readChar(); /* skip line separator */
System.out.println("item: " + item + " price:"+ price + " quantity: " + qty);
}
}
catch (EOFException e)
{
in.close();
}
}
}
In line 11, we create a FileInputStream object, fileIn, in the usual way. In line 12,we use the DataInputStream constructor to create an object, in, to wrap the
FileInputStream, fileIn. With a DataInputStream, we cannot use –1 to indicate we have reached the end of a file. Instead, we use try catch statements that handle the EOFException that is raised
when any of the DataInputStream read methods reach the end of the file. Within the try statement, we start an infinite loop in line 14.
In lines 15–18, we use the DataInputStream.readChar method to read a single character, singlechar, from the stream. Each character is appended to the variable item, a StringBuffer data type, until we read a field separator.
In line 19, we read the price from the stream using the DataInputStream.readFloat method. We use the readChar method to skip the field separator (line 20), then read the quantity using the readInt method (line 21). We use the readChar method again to skip the line separator (line 22), then in lines 23–24 print the file contents for the current line to the standard output stream.
Java DataInputStream Example
Tags
# DataInputStream Example
# Input/Output
Share This
Input/Output
Labels:
DataInputStream Example,
Input/Output
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment