Java Tutorials
  • Introduction to Java
    • What is Java?
    • History and Features of Java
    • Java Virtual Machine (JVM) and Bytecode
    • Why Java?
  • Setting up Java Development Environment
    • Installing Java Development Kit (JDK)
    • JDK vs JRE
    • Setting up IDE (Eclipse, IntelliJ, NetBeans) or Text Editor (VS Code, Sublime Text)
  • Basic Java
    • First Java Program : Hello World
    • Variable
    • Data Type
    • Constant
    • Date and Format
    • Operator
    • Condition
    • Looping
    • Function
    • Variadic Function
    • Enums
    • Array
    • Collection
    • Exception and Exception Handling
    • Naming Convention
  • Object Oriented Programming (OOP)
    • Classes and Objects
    • Inheritance and Polymorphism
    • Encapsulation and Abstraction
  • File Handling
    • Reading and Writing Binary File
    • Reading and Writing Text File
    • Serialization and Deserialization
  • Multithreading
    • Creating and Running Threads
    • Synchronization
    • Thread Pools and Executors
  • Collections API
    • Sorting and Comparable
    • Searching and Comparator
  • Java Database Connectivity (JDBC)
    • Introduction and Life Cycle
    • Connection to Database (MySQL)
    • Downloading JDBC Drivers for Various Databases
    • Maven and Gradle JDBC Drivers for Various Databases
    • JDBC URL Formats
    • Statement and PreparedStatement
    • CallableStatement
    • Selecting Data using JDBC
    • Inserting Data using JDBC
    • Updating Data using JDBC
    • Deleting Data using JDBC
    • Invoking Function and Stored Procedure using JDBC
  • Lambda
    • Introduction to Lambda Expressions
    • Functional Interface
    • Filtering, Mapping, Reducing
    • Lambda Expressions in Collections
    • Method References
    • Functional Programming Concepts
    • Stream API
    • Error Handling in Lambda Expressions
    • Optional in Functional Programming
    • Parallel Processing with Lambda
    • Functional Programming Patterns
    • Advanced Topics in Lambda Expressions
    • Best Practices and Design Patterns
    • Real-World Use Cases and Examples
Powered by GitBook
On this page
  1. File Handling

Reading and Writing Binary File

Reading and writing binary files in Java involves dealing with raw binary data, which is common when working with image files, audio files, or any other non-text files. Here's a detailed explanation along with examples for reading and writing binary files.

1. Reading Binary Files (Using FileInputStream):

import java.io.FileInputStream;
import java.io.IOException;

public class ReadBinaryFile {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("input.bin")) {
            int data;
            while ((data = fis.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, FileInputStream is used to read binary data from the "input.bin" file. The read() method reads a byte of data and returns -1 when the end of the file is reached.

2. Writing Binary Files (Using FileOutputStream):

import java.io.FileOutputStream;
import java.io.IOException;

public class WriteBinaryFile {
    public static void main(String[] args) {
        String content = "Hello, Binary File!";
        try (FileOutputStream fos = new FileOutputStream("output.bin")) {
            byte[] bytes = content.getBytes();
            fos.write(bytes);
            System.out.println("Data written to the file.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, FileOutputStream is used to write binary data to the "output.bin" file. The string content is converted to bytes using the getBytes() method, and the write(byte[]) method is used to write the data.

Explanation:

  • Reading Binary Files:

    • FileInputStream is used to read binary data from files.

    • read() method reads a byte of data from the input stream. It returns -1 if there is no more data because the end of the file has been reached.

  • Writing Binary Files:

    • FileOutputStream is used to write binary data to files.

    • Data is first converted to bytes using methods like getBytes().

    • write(byte[]) method is used to write the byte array to the output stream.

Important Notes:

  • Binary file reading and writing is typically used for non-text files (like images, audio, video, etc.) where raw binary data needs to be preserved.

  • Always handle exceptions properly to ensure your file operations are robust and can handle any potential issues that may arise during reading and writing.

These examples provide a fundamental understanding of how to read and write binary files in Java. Always close the streams after using them to release system resources.

PreviousEncapsulation and AbstractionNextReading and Writing Text File

Last updated 1 year ago