Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Tuesday, March 11, 2025

Input / Output Basics in Java


Java provides an extensive framework for performing input and output (I/O) operations on various data sources like files, console, network connections, etc. The Java I/O system is built around streams which handle input and output of data.


📌 Streams in Java

  • A stream is a sequence of data (either bytes or characters).
  • Streams can be Input Streams (used for reading data) or Output Streams (used for writing data).

📌 Types of Streams

1. Byte Streams

  • Used for handling raw binary data (images, audio, video, etc.).
  • Classes:
    • InputStream (Abstract class): Provides methods to read bytes from a source.
    • OutputStream (Abstract class): Provides methods to write bytes to a destination.

Common Byte Stream Classes:

Class

Description

FileInputStream

Reads raw bytes from a file.

FileOutputStream

Writes raw bytes to a file.

BufferedInputStream

Enhances efficiency by buffering.

BufferedOutputStream

Enhances efficiency by buffering.


2. Character Streams

  • Designed for handling text data (strings, characters).
  • Automatically converts between Unicode and local character sets.
  • Classes:
    • Reader (Abstract class): Provides methods to read characters from a source.
    • Writer (Abstract class): Provides methods to write characters to a destination.

Common Character Stream Classes:

Class

Description

FileReader

Reads text from a file.

FileWriter

Writes text to a file.

BufferedReader

Buffers characters for efficiency.

BufferedWriter

Buffers characters for efficiency.


📌 Reading and Writing Console (Standard I/O)

Reading from Console (Scanner Class)

import java.util.Scanner;

 

public class ConsoleInputExample {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

       

        System.out.print("Enter your name: ");

        String name = scanner.nextLine();

       

        System.out.print("Enter your age: ");

        int age = scanner.nextInt();

       

        System.out.println("Hello, " + name + "! You are " + age + " years old.");

  

        scanner.close();

    }

}


Writing to Console (System.out)

public class ConsoleOutputExample {

    public static void main(String[] args) {

        System.out.println("Hello, World!");      // Prints with newline

        System.out.print("Hello, ");               // Prints without newline

        System.out.printf("My age is %d years.", 25); // Prints formatted text

    }

}


📌 Reading and Writing Files

Reading from Files (Using FileReader and BufferedReader)

import java.io.*;

 

public class FileReadingExample {

    public static void main(String[] args) {

        try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {

            String line;

            while ((line = reader.readLine()) != null) {

                System.out.println(line);

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}


Writing to Files (Using FileWriter and BufferedWriter)

import java.io.*;

 

public class FileWritingExample {

    public static void main(String[] args) {

        try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"))) {

            writer.write("This is a test message.");

            writer.newLine();

            writer.write("File Writing in Java is easy!");

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}


Reading and Writing Files with Byte Streams

import java.io.*;

 

public class ByteStreamExample {

    public static void main(String[] args) {

        // Writing a file using FileOutputStream

        try (FileOutputStream fos = new FileOutputStream("output.dat")) {

            fos.write("This is binary data.".getBytes());

        } catch (IOException e) {

            e.printStackTrace();

        }

 

        // Reading a file using FileInputStream

        try (FileInputStream fis = new FileInputStream("output.dat")) {

            int content;

            while ((content = fis.read()) != -1) {

                System.out.print((char) content);

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}


📌 File Class (File Handling)

The File class in Java is part of the java.io package. It is an abstract representation of file and directory pathnames.

Creating and Deleting Files

import java.io.File;

import java.io.IOException;

 

public class FileHandlingExample {

    public static void main(String[] args) {

        try {

            // Creating a file

            File file = new File("newFile.txt");

            if (file.createNewFile()) {

                System.out.println("File created: " + file.getName());

            } else {

                System.out.println("File already exists.");

            }

 

            // Deleting a file

            if (file.delete()) {

                System.out.println("File deleted: " + file.getName());

            } else {

                System.out.println("Failed to delete the file.");

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}


📌 Important Points to Remember

  1. Streams are Auto-Closeable: Always close the streams to avoid resource leaks.
  2. Use try-with-resources statement: Recommended way to manage resources.
  3. Character Streams are better for text data: Automatically handles encoding and decoding.
  4. Byte Streams are better for binary data: For images, videos, etc.
  5. Use BufferedReader and BufferedWriter for efficiency: Buffered I/O is much faster.

 

No comments:

Post a Comment