Java Input and Output Operations


Java Input and Output Operations

Java's Input and Output (I/O) system enables communication between a program and the external world, such as reading input from a user, files, or other sources and outputting information to the console or files. The java.io package provides a comprehensive set of classes for handling I/O operations.


1. Input Operations

Input operations allow you to read data from external sources, such as the keyboard, files, or network streams. Below are common ways to handle input in Java:

Reading Input from Console

Class Used: Scanner (from java.util package)

Example:

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 studentname = scanner.nextLine(); // Captures an entire line of input
        
        System.out.print("Enter your age: ");
       
        int studentage = scanner.nextInt(); // Retrieves an integer from input

        System.out.println("Name: " + name + ", Age: " + age);
        scanner.close();
    }
}

Explanation:

  • nextLine() reads a full line of text.
  • nextInt() reads an integer.
  • Always close the Scanner object to free resources.

2. Output Operations

Output operations enable writing data to external destinations, such as the console or a file.

Writing Output to Console

Class Used: System.out

Example:

public class ConsoleOutputExample {
    public static void main(String[] args) {
        System.out.println("Hello, World!");  // Displays a message followed by a newline
        System.out.print("This is a test.");  // Prints without adding a newline
        System.out.printf("Formatted number: %.2f", 123.456); // Outputs a formatted number
    }
}

Explanation:

  • println() appends a newline after displaying the output.
  • print() keeps the output on the same line without adding a newline.
  • printf() is used for formatted output.

Writing Output to a File

Class Used: FileWriter and BufferedWriter

Example:

import java.io.*;

public class FileOutputExample {
    public static void main(String[] args) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) { // Uses a buffered writer for file output
            writer.write("This is a test message.");
            writer.newLine();  // Adds a new line
            writer.write("File writing in Java is simple!");
        } catch (IOException e) {
            System.out.println("File writing error: " + e.getMessage());
        }
    }
}

Explanation:

  • FileWriter writes character-based data to a file.
  • BufferedWriter enhances performance by buffering data before writing to a file.

3. Advanced I/O Operations

Java also supports advanced I/O through classes like DataInputStream, DataOutputStream, ObjectInputStream, and ObjectOutputStream for handling primitive data types or objects.

Example: Writing and Reading Binary Data

import java.io.*;

public class BinaryIOExample {
    public static void main(String[] args) {
        // Writing binary data
        try (DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.bin"))) { // Writes binary data to a file
            dos.writeInt(42);  // Writes an integer
            dos.writeDouble(3.14159);  // Writes a double
        } catch (IOException e) {
            System.out.println("Error occurred while writing binary data: " + e.getMessage());
        }

        // Reading binary data
        try (DataInputStream dis = new DataInputStream(new FileInputStream("data.bin"))) { // Reads binary data from a file
            int number = dis.readInt();  // Reads an integer
            double value = dis.readDouble();  // Reads a double
            System.out.println("Number: " + number + ", Value: " + value);
        } catch (IOException e) {
            System.out.println("Error reading binary data: " + e.getMessage());
        }
    }
}

Explanation:

  • DataOutputStream and DataInputStream handle primitive data types in binary format.
  • Files generated by this method are not human-readable.

Summary of Common I/O Classes

Class NamePurpose
ScannerReading input from console or files
BufferedReaderEfficient reading of text data
FileReaderReading character-based data from files
FileWriterWriting character-based data to files
DataInputStreamReading primitive data in binary form
DataOutputStreamWriting primitive data in binary form
ObjectInputStreamReading serialized objects
ObjectOutputStreamWriting serialized objects
PreviousNext