Java DataOutputStream Example

The WriteBinFile example writes out an order to a file File1.dat. The order consists of a number of lines; each line is made up of an item, price, and quantity ordered as follows:

ice axe;74.99;2
crampons;44.95;1
sleeping bag;100.00;1
mittens;37.50;3


A semicolon is used as a field separator.

WriteBinFile

import java.io.*;

public class WriteBinFile
{


public static void main(String[] args) throws
IOException
{
FileOutputStream fileOut = new FileOutputStream(“File1.dat”);
DataOutputStream out= new DataOutputStream(FileOut);
String[] item = {"ice axe", "crampons",
"sleeping bag", "mittens"};
float[] price = {74.99f, 44.95f, 100.00f, 37.50f};
int[] qty = {2, 1, 1, 3};
char fieldSeparator = ';';
char lineSeparator = '\n';
int i;
for (i = 0; i < 4; i++)
{
out.writeChars(item[i]);
out.writeChar(fieldSeparator);
out.writeFloat(price[i]);
out.writeChar(fieldSeparator);
out.writeInt(qty[i]);
out.writeChar(lineSeparator);
}
out.close();
}
}


In lines 7–8, we create a FileOutputStream object, fileOut, in the usual way.

In line 9, we use the DataOutputStream constructor to create an object, out, to wrap the FileOutputStream, fileOut.

In lines 10–13, we create a String array, item, holding the four items, a float array, price, holding the four prices, and an int array, qty, holding the four quantities. In lines
14–15, we define field and line separators.

In lines 17–24, we use a for loop to output the four lines to the DataOutputStream. For each line, we use the following methods from the java.io.DataOutputStream class:


writeChars outputs a String data type, in this case, item
writeChar outputs a char data type, in this case, the field separator
writeFloat outputs a float data type, in this case, price
writeChar outputs another field separator
writeInt outputs an int data type, in this case, qty
writeChar outputs the line separator

No comments:

Post a Comment