Binary Files and Streams

Binary Files and Data Streams

Binary Representation

  • Each character is represented by 8 bits.
  • In programming a character can be represented as 0000000000000000. Eight zeros or eight ones representing a Character.

Binary Files

  • Binary files deal with binary data.
  • Storing data in binary format is more efficient.

Writing to Binary Files

Basic Functionality:
  • Writing bytes to a file.
  • Writing an integer array to a file.
Classes and Statements:
  • FileOutputStream
  • DataOutputStream
Example:
import java.io.*;

public class BinaryFileWriter {
    public static void main(String[] args) {
        try {
            //  Create a FileOutputStream to write to a file
            FileOutputStream fileOut = new FileOutputStream("numbers.dat");

            //  Wrap the FileOutputStream with a DataOutputStream to write binary data
            DataOutputStream dataOut = new DataOutputStream(fileOut);

            // Sample integer array
            int[] numbers = {1, 2, 3, 4, 5};

            // Write the integers to the binary file
            for (int number : numbers) {
                dataOut.writeInt(number);
            }

            // Close the DataOutputStream
            dataOut.close();

            System.out.println("Successfully wrote integers to numbers.dat");

        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}
  • The code shows how to use DataOutputStream and FileOutputStream to write information to a binary file.
  • A loop is needed to iterate through an array and write each element to the file.

Reading from Binary Files

Input Streams:
  • FileInputStream
  • Wrap a FileInputStream with a DataInputStream.
Reading Data:
  • Use input streams to get data from a file.