DataOutputStream is filter streams that is used to write strings and primitive data types comprised of more than a single byte. DataOutputStream implement the DataOutput interface. This interface defines methods for writing strings and all of the Java primitive types, including numbers and Boolean values.
We can construct a DataOutputStream from an OutputStream and then use a method such as writeInt(), writeDouble, writeFloat() etc to write primitive data types as follows:
DataOutputStream dins = new DataOutputStream(FileOutputStream file);
dins.writeInt();
dins.writeFloat();
dins.writeDouble();
Consider the following example which opens a text file and writes primitive data types such as int, double to a text file file2.txt.
Example:
/**
From dataOutputStream.java
*/
import java.io.DataOutputStream;
import java.io.FileOutputStream;
/**
*
* @author JavaHotSpot
*/
public class dataOutputStream
{
public static void main(String args[])
{
try
{
int[] roll={1,2,3,4,5};
double[] percentage={98.34,97.32,89.65,87.34,78.12};
FileOutputStream fs = new FileOutputStream("C:\\file2.txt");
DataOutputStream ds = new DataOutputStream(fs);
for(int i=0;i<roll.length;i++)
{
ds.writeInt(roll[i]);
ds.writeDouble(percentage[i]);
}
System.out.append("Done...!");
}
catch(Exception ex)
{
System.err.println(ex);
}
}
}
Output: