articles

Home / DeveloperSection / Articles / Java I/O Streams: Working with Files and Input/Output Operations

Java I/O Streams: Working with Files and Input/Output Operations

Java I/O Streams: Working with Files and Input/Output Operations

Ravi Vishwakarma 195 23-Jul-2024

Java's I/O (Input/Output) streams provide a powerful and flexible way to handle input and output operations. The Java I/O package (java.io) includes a variety of classes for reading from and writing to files, managing data streams, and performing other I/O operations.

Types of Streams

Java I/O is based on two main types of streams:

  1. Byte Streams: Handle I/O of raw binary data.
    • InputStream: Abstract class for reading byte streams.
    • OutputStream: Abstract class for writing byte streams.
  2. Character Streams: Handle I/O of character data, supporting Unicode.
    • Reader: Abstract class for reading character streams.
    • Writer: Abstract class for writing character streams.

 

Java I/O Streams: Working with Files and Input/Output Operations

 

Byte Streams

Reading from a File

Using FileInputStream to read bytes from a file:

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

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

Writing to a File

Using FileOutputStream to write bytes to a file:

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

public class ByteStreamExample {
    public static void main(String[] args) {
        String data = "Hello, World!";
        try (FileOutputStream fos = new FileOutputStream("example.txt")) {
            fos.write(data.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Character Streams

Reading from a File

Using FileReader to read characters from a file:

import java.io.FileReader;
import java.io.IOException;

public class CharacterStreamExample {
    public static void main(String[] args) {
        try (FileReader fr = new FileReader("example.txt")) {
            int data;
            while ((data = fr.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Writing to a File

Using FileWriter to write characters to a file:

import java.io.FileWriter;
import java.io.IOException;

public class CharacterStreamExample {
    public static void main(String[] args) {
        String data = "Hello, World!";
        try (FileWriter fw = new FileWriter("example.txt")) {
            fw.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Buffered Streams

Buffered streams provide a way to read and write data more efficiently by using a buffer.

BufferedReader and BufferedWriter

Using BufferedReader and BufferedWriter to read and write text efficiently:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedStreamExample {
    public static void main(String[] args) {
        // Writing to a file using BufferedWriter
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("example.txt"))) {
            bw.write("Hello, World!");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Reading from a file using BufferedReader
        try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Data Streams

Data streams allow you to read and write primitive Java data types (int, float, double, etc.) in a portable way.

DataInputStream and DataOutputStream

Using DataInputStream and DataOutputStream to read and write primitive data types:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataStreamExample {
    public static void main(String[] args) {
        // Writing primitive data types to a file
        try (DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.dat"))) {
            dos.writeInt(123);
            dos.writeDouble(45.67);
            dos.writeBoolean(true);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Reading primitive data types from a file
        try (DataInputStream dis = new DataInputStream(new FileInputStream("data.dat"))) {
            int intValue = dis.readInt();
            double doubleValue = dis.readDouble();
            boolean booleanValue = dis.readBoolean();
            System.out.println("Read values: " + intValue + ", " + doubleValue + ", " + booleanValue);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Summary

  • Byte Streams (InputStream and OutputStream): Handle raw binary data.
  • Character Streams (Reader and Writer): Handle character data.
  • Buffered Streams (BufferedReader and BufferedWriter): Improve efficiency by buffering input and output.
  • Data Streams (DataInputStream and DataOutputStream): Read and write primitive data types.

Understanding and utilizing these different types of streams allows you to handle various I/O operations in Java efficiently and effectively.

 

Read more 

Explain the Stream API introduced in Java 8. How does it work?

Java Memory Management: Understanding Stack and Heap

Java Streams API: Intermediate and Terminal Operations


Updated 23-Jul-2024
Hi, my self Ravi Vishwakarma. I have completed my studies at SPICBB Varanasi. now I completed MCA with 76% form Veer Bahadur Singh Purvanchal University Jaunpur. SWE @ MindStick | Software Engineer | Web Developer | .Net Developer | Web Developer | Backend Engineer | .NET Core Developer

Leave Comment

Comments

Liked By