DEV Community

Cover image for Writing Data to a Binary File in Java
Shashi Preetham
Shashi Preetham

Posted on

Writing Data to a Binary File in Java

Binary Files

Computers are based on the binary numbering system, which consists of just two unique numbers, 0 and 1. All operations that are possible in the decimal system (addition, subtraction, multiplication, division) are equally possible in the binary system.

A binary file is computer-readable but not human-readable. All executable programs are stored in binary files, as are most numeric data files. In contrast, text files are stored in a form (usually ASCII) that is human-readable.

Writing Data to A Binary File

Accepting the data values from the console and sending them from memory buffer to a secondary storage device. It deals with all types of primitive data viz. short, int, long, float, double, char, boolean, and String. In this system, the data are stored in terms of bytes in the secondary storage devices.
Follow the following steps while creating a binary file:

1. Create the file in output stream mode along with the stream object.

Syntax:
FileOutputStream <object> = new FileOutputStream <file name>

For example,

FileOutputStream fout = new FileOutputStream("example.dat");
Enter fullscreen mode Exit fullscreen mode

The extension of the file name (.dat) signifies the type of data that is stored in the output stream mode in the hard disk.

2. Create a link between the object of the FileOutputStream with the buffer output stream.

Syntax:
DataOutputStream <object> = new DataOutputStream(FileOutputStream object);

For example:

DataOutputStream dout = new DataOutputStream(fout);
Enter fullscreen mode Exit fullscreen mode

3. Accept the required data from the console in one of the two ways:

(a) Using stream reader by importing java.io.*
(b) Using Scanner class by importing java.util.*

4. Write the data in the secondary storage with the help of these commands:

  • To write short type data - <object>.writeShort<variable name>
  • To write integer type data - <object>.writeInt<variable name>
  • To write long type data - <object>.writeLong<variable name>
  • To write float type data - <object>.writeFloat<variable name>
  • To write double type data - <object.writeDouble<variable name>
  • To write character type data - <object>.writeChar<variable name>
  • To write string type data - <object>.writeUTF<variable name>

(UTF stands for Unicode Transformed Format string)

5. Close the data file using FileOutputStream object as:

<object>.close();
Enter fullscreen mode Exit fullscreen mode

Sample Program

An Electronic Store wants to make an inventory of all types of products in a binary file "inventory.dat" to input product name, product code, quantity of product and price.
Following is a program to create a binary file to perform the above task.

import java.io.*;
public class sample {
    public static void main(String args[]) throws IOException {
        BufferedReader ob=new BufferedReader(new InputStreamReader(System.in));

        // Creating binary file
        FileOutputStream fout=new FileOutputStream("inventory.dat");
        DataOutputStream dout=new DataOutputStream(fout);

        int n, q, pr;
        String str, pc;
        System.out.println("Enter number of products:");
        n=Integer.parseInt(ob.readLine());
        for(int i=1;i<=n;i++) {
            System.out.println("Enter product name");
            str=ob.readLine();
            System.out.println("Enter product code");
            pc=ob.readLine();
            System.out.println("Enter product quantity");
            q=Integer.parseInt(ob.readLine());
            System.out.println("Enter price");
            pr=Integer.parseInt(ob.readLine());

            // Writing data values from memory to binary file
            dout.writeUTF(str);
            dout.writeUTF(pc);
            dout.writeInt(q);
            dout.writeInt(pr);
        }
        // Closing binary file object
        fout.close();
        dout.close();
        ob.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)