Java

I/O Streams

Java / I/O Streams

I/O Streams

Input/Output Streams

In Java, streams are used to perform input and output operations. A stream is a sequence of data that flows from one place to another.

  • Input Stream → Reads data into the program
  • Output Stream → Writes data from the program

Types of Streams

1. Byte Streams

Byte Streams work with raw binary data, such as images, audio files, videos, and PDF files.

  • They read and write data one byte at a time
  • They are used for non-text files

2. Character Streams

Character Streams work with text data (characters and strings).

  • They read and write data character by character
  • They automatically handle character encoding (like UTF-8)

 

FileInputStream

FileInputStream in Java is used to read data from a file in the form of bytes. It is a type of byte stream, which reads data in its raw binary form such as images, audio files, videos, or PDF files.

You may have already used the Scanner class to read text files. Scanner is very easy and useful for reading text because it can split data into lines, words, or numbers. However, when you need more control or when working with binary data (non-text files), Scanner is not suitable.

 

Example

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

public class Main {
 public static void main(String[] args) {

   try {
     // Creating FileInputStream object to read file
     FileInputStream fis = new FileInputStream("filename.txt");

     int data;

     // Reading file byte by byte
     while ((data = fis.read()) != -1) {
       System.out.print((char) data); // converting byte to character
     }

     // Closing the stream
     fis.close();

   } catch (IOException e) {
     System.out.println("An error occurred.");
   }
 }
}

FileOutputStream

FileOutputStream in Java is used to write data into a file in the form of bytes. It is a type of byte stream, which writes data in raw binary form.

FileOutputStream is a Java class used to write data into a file in byte form, especially for both text and binary files like images, audio, videos, and PDFs.

Example

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

public class Main {
 public static void main(String[] args) {

   try {
     // Creating FileOutputStream object to write data into file
     FileOutputStream fos = new FileOutputStream("output.txt");

     String data = "Hello, this is FileOutputStream example!";

     // Converting string into bytes and writing into file
     fos.write(data.getBytes());

     // Closing the stream
     fos.close();

     System.out.println("Data written successfully.");

   } catch (IOException e) {
     System.out.println("An error occurred.");
   }
 }
}

Technology
Java
want to connect with us ?
Contact Us