Home Tutorial Java Core Files Java File Binary

 
 

Share on Google+Share on Google+
Java File Binary
Posted on: April 14, 2006 at 12:00 AM
Advertisement
In this section, you will learn how to write numeric data into the binary file.

Java File Binary

In this section, you will learn how to write numeric data into the binary file.

Description of code:

Numeric data converts compactly and faster in a binary format than the text. In the given example, at first, we have created two arrays, integer and double type. Then we have opened the FileOutputStream and specify the file to create. This stream is then wrapped with an instance of DataOutputStream which contains several useful methods for writing primitive data into the file.

Here is the code:

import java.io.*;

public class JavaFileBinary {
	public static void main(String arg[]) throws Exception {
		int[] arr1 = { 1, 2, 3, 4, 5 };
		double[] arr2 = { 1.5, 2.5, 3.5, 4.5, 5.5 };
		File file = new File("C:/student.dat");
		FileOutputStream fos = new FileOutputStream(file);
		DataOutputStream dos = new DataOutputStream(fos);
		for (int i = 0; i < arr1.length; i++) {
			dos.writeInt(arr1[i]);
			dos.writeDouble(arr2[i]);
		}
		dos.close();
	}
}

In the above code, the methods writeInt (int i) and the writeDouble (double d) of class DataOutputStream methods provides the way to write the data to the file.

Advertisement

Related Tags for Java File Binary:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 14, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com