;
Java Basics July 21 ,2025

Input/Output in Java

1. Introduction to I/O in Java

I/O (Input/Output) in Java refers to the mechanism of receiving data (input) from sources like the keyboard, files, or network, and sending data (output) to destinations like the console, files, or network sockets.

Java provides a powerful and flexible set of classes to handle I/O operations, found mainly in the java.io and java.util packages.

Why Learn Java I/O?

  • Every real-world application needs to interact with users, files, or systems.
  • Enables features like reading user inputs, saving application data, reading configuration files, etc.

Java supports two main kinds of I/O streams:

  • Byte Streams (for binary data) – use InputStream and OutputStream
  • Character Streams (for text data) – use Reader and Writer

Before diving into files and advanced topics, let’s begin with standard input and output — reading from the console and printing to it.

2. Standard I/O in Java

Java provides basic input and output capabilities through the Scanner class (for input) and System.out.println() (for output).

2.1 Output using System.out.println()

This is the most common way to print output to the console.

public class OutputExample {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
        System.out.print("This is printed without a new line. ");
        System.out.println("This continues on the same line.");
    }
}

Explanation:

  • System.out.println() prints the message and moves the cursor to the next line.
  • System.out.print() prints the message without moving to a new line.

2.2 Input using Scanner

The Scanner class (from java.util package) is used to read input from various sources, including the console.

✅ Import the Scanner class:

import java.util.Scanner;

✅ Create a Scanner object:

Scanner sc = new Scanner(System.in);

✅ Read input:

String name = sc.nextLine();  // reads a line of text
int age = sc.nextInt();       // reads an integer
double salary = sc.nextDouble(); // reads a decimal

🔍 Full Example:

import java.util.Scanner;

public class InputExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = sc.nextLine();

        System.out.print("Enter your age: ");
        int age = sc.nextInt();

        System.out.print("Enter your salary: ");
        double salary = sc.nextDouble();

        System.out.println("\nHello " + name + "!");
        System.out.println("Your age: " + age);
        System.out.println("Your salary: ₹" + salary);
    }
}

Common Scanner Methods

MethodDescription
next()Reads a single word (until space)
nextLine()Reads a full line (until Enter)
nextInt()Reads an integer
nextDouble()Reads a double
nextBoolean()Reads a boolean

⚠️ Caution: Mixing nextLine() with other inputs

If you use nextLine() after reading other data types like nextInt() or nextDouble(), you may face input skipping. Always consume the leftover newline character.

sc.nextLine(); // Consume the leftover newline

 

2. Types of I/O in Java

Java provides different classes and mechanisms to handle Input and Output (I/O) depending on the kind of data being read or written. These are mainly grouped into two types:

1. Byte Streams

  • Handle binary data (like images, audio, video, PDFs, etc.)
  • Based on InputStream and OutputStream classes
  • Ideal for low-level I/O operations

Common Byte Stream Classes:

ClassDescription
FileInputStreamReads bytes from a file
FileOutputStreamWrites bytes to a file
BufferedInputStreamImproves reading efficiency
BufferedOutputStreamImproves writing efficiency
DataInputStreamReads primitive Java data types
DataOutputStreamWrites primitive Java data types

Example:

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class ByteStreamExample {
    public static void main(String[] args) {
        try {
            FileInputStream input = new FileInputStream("input.txt");
            FileOutputStream output = new FileOutputStream("output.txt");

            int data;
            while ((data = input.read()) != -1) {
                output.write(data);
            }

            input.close();
            output.close();
            System.out.println("File copied successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2. Character Streams

  • Handle text data (characters, strings, lines)
  • Based on Reader and Writer classes
  • Ideal for text-based files

Common Character Stream Classes:

ClassDescription
FileReaderReads characters from a file
FileWriterWrites characters to a file
BufferedReaderEfficiently reads text lines
BufferedWriterEfficiently writes text lines
PrintWriterWrites formatted text (like System.out)

Example:

import java.io.FileReader;
import java.io.FileWriter;

public class CharStreamExample {
    public static void main(String[] args) {
        try {
            FileReader fr = new FileReader("input.txt");
            FileWriter fw = new FileWriter("output.txt");

            int ch;
            while ((ch = fr.read()) != -1) {
                fw.write(ch);
            }

            fr.close();
            fw.close();
            System.out.println("Text copied using character streams.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

✅ Summary of Byte vs Character Streams:

FeatureByte StreamCharacter Stream
Base classesInputStream / OutputStreamReader / Writer
Data handledBinary (images, PDF, audio)Text (characters, strings)
Use caseLow-level I/OHigh-level text processing
Example classFileInputStreamFileReader

3. Reading Input from the Console

Console input is essential for interactive applications where the user provides input at runtime. Java provides two main ways to read input from the console:

A. Using Scanner Class

This is the most commonly used method for beginners and general applications.

✅ Key Features:

  • Easy to use
  • Supports multiple data types
  • Belongs to the java.util package

✅ Import and Create Scanner:

import java.util.Scanner;
Scanner sc = new Scanner(System.in);

✅ Reading Input:

System.out.print("Enter your name: ");
String name = sc.nextLine();

System.out.print("Enter your age: ");
int age = sc.nextInt();

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

⚠️ Common Issue:

When using nextInt(), nextDouble() etc., if you want to read a line afterward, use sc.nextLine() to consume the leftover newline.

sc.nextLine(); // to consume leftover newline before using nextLine again

B. Using BufferedReader and InputStreamReader

This is a more traditional and performance-oriented approach, especially useful when reading large text input.

✅ Key Classes:

  • BufferedReader → used to read text from a character-based input stream.
  • InputStreamReader → bridges byte streams to character streams.

✅ Example:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class ConsoleInputExample {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(
            new InputStreamReader(System.in)
        );

        System.out.print("Enter your city: ");
        String city = reader.readLine(); // reads entire line

        System.out.print("Enter your pin code: ");
        int pin = Integer.parseInt(reader.readLine()); // parse string to int

        System.out.println("You live in " + city + " - " + pin);
    }
}

⚠️ Notes:

  • You need to handle IOException
  • Always convert input using Integer.parseInt(), Double.parseDouble() etc., since readLine() returns String

✅ When to Use What?

RequirementUse ScannerUse BufferedReader
Small input, beginner use✔️ Easy to use✘ Requires exception handling
High-speed input needed✘ Slower for large data✔️ Faster with buffering
Supports multiple types✔️ Built-in parsing methods✘ Manual parsing required
Input as text only✔️✔️

Great! Let’s now move to the 4th point from the I/O index:

4. Writing Output to the Console

In Java, console output is primarily done using:

  1. System.out.print()
  2. System.out.println()
  3. System.out.printf()
  4. PrintStream (advanced formatting and output)

These methods allow Java programs to display messages, variable values, and formatted output to the screen.

A. Using System.out.print() and System.out.println()

✅ System.out.print()

  • Prints output without moving the cursor to the next line.
System.out.print("Hello");
System.out.print(" World");  // Output: Hello World

✅ System.out.println()

  • Prints output and moves the cursor to a new line.
System.out.println("Hello");
System.out.println("World");  
// Output:
// Hello
// World

✅ Mixing text and variables:

String name = "Saumya";
int age = 21;
System.out.println("Name: " + name + ", Age: " + age);

B. Using System.out.printf() for Formatted Output

This method provides C-style formatting using format specifiers like %d, %s, %.2f, etc.

✅ Example:

String product = "Pen";
double price = 12.5;

System.out.printf("Product: %s, Price: ₹%.2f", product, price);
// Output: Product: Pen, Price: ₹12.50

✅ Common Format Specifiers:

SpecifierDescription
%dInteger
%fFloat/Double
%.2fFloat with 2 decimal places
%sString
%nNew line (platform-independent)

C. Using PrintStream (Optional/Advanced)

Java’s System.out is actually a PrintStream object.

You can create your own PrintStream and write output to files or other destinations.

Example (custom PrintStream):

import java.io.*;

public class CustomPrintStream {
    public static void main(String[] args) {
        try {
            PrintStream ps = new PrintStream("output.txt");
            ps.println("This line is written to a file.");
            ps.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

5. File Handling Basics in Java

File handling allows a Java program to create, read, write, and delete files. Java provides robust file I/O support through the java.io and java.nio packages.

We’ll cover:

  • Creating a file
  • Writing to a file
  • Reading from a file
  • Checking if a file exists
  • Deleting a file

A. Creating a File

You can create a file using the File class from the java.io package.

✅ Example:

import java.io.File;
import java.io.IOException;

public class CreateFileExample {
    public static void main(String[] args) {
        try {
            File file = new File("example.txt");
            if (file.createNewFile()) {
                System.out.println("File created: " + file.getName());
            } else {
                System.out.println("File already exists.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • createNewFile() creates a new file if it doesn’t exist.
  • Always handle IOException when dealing with file creation.

B. Writing to a File

You can write text using the FileWriter or BufferedWriter.

✅ Example using FileWriter:

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

public class WriteToFile {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("example.txt");
            writer.write("Hello, this is a sample text written to the file.");
            writer.close();
            System.out.println("Successfully written to the file.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Notes:

  • FileWriter overwrites existing content. Use new FileWriter("example.txt", true) to append.
  • Always close the writer.

C. Reading from a File

You can read data using Scanner, BufferedReader, or FileReader.

✅ Example using Scanner:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFileExample {
    public static void main(String[] args) {
        try {
            File file = new File("example.txt");
            Scanner sc = new Scanner(file);
            while (sc.hasNextLine()) {
                String data = sc.nextLine();
                System.out.println(data);
            }
            sc.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

D. Checking if a File Exists

File file = new File("example.txt");
if (file.exists()) {
    System.out.println("File exists.");
} else {
    System.out.println("File does not exist.");
}

E. Deleting a File

File file = new File("example.txt");
if (file.delete()) {
    System.out.println("File deleted successfully.");
} else {
    System.out.println("Failed to delete the file.");
}
TaskClass UsedKey Method/Function
Create a fileFilecreateNewFile()
Write to a fileFileWriterwrite(), close()
Read a fileScanner, FileReadernextLine(), read()
Check fileFileexists()
Delete fileFiledelete()

6. FileReader & FileWriter (Character Stream I/O)

Java provides character-oriented classes for reading and writing files. These classes handle text data and are suitable when you're working with character-based content, like .txt files.

The two primary classes are:

  • FileReader – for reading characters from a file
  • FileWriter – for writing characters to a file

These classes are part of the java.io package.

A. FileWriter – Writing Characters to a File

The FileWriter class writes character data to a file.

✅ Syntax:

FileWriter writer = new FileWriter("filename.txt");

✅ Example:

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

public class FileWriterExample {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("notes.txt");
            writer.write("Java FileWriter example.\nWriting to a file is simple.");
            writer.close();
            System.out.println("Data written successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

✅ Notes:

  • write() method is used to write strings or characters.
  • Always call close() to flush and close the stream.
  • To append data, use:

    FileWriter writer = new FileWriter("filename.txt", true);
    

B. FileReader – Reading Characters from a File

The FileReader class is used to read character data from a file.

✅ Syntax:

FileReader reader = new FileReader("filename.txt");

✅ Example:

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

public class FileReaderExample {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("notes.txt");
            int ch;
            while ((ch = reader.read()) != -1) {
                System.out.print((char) ch);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

✅ Explanation:

  • read() returns the next character as an integer. It returns -1 when the end of file is reached.
  • Cast the integer to char to display the actual character.

✅ Comparison Table

FeatureFileWriterFileReader
PurposeWriting characters to fileReading characters from file
Packagejava.iojava.io
Key Methodswrite(), close()read(), close()
Use CaseSaving logs, messages, etc.Reading configuration, text files

7. BufferedReader & BufferedWriter (Efficient I/O)

When working with large files or handling multiple read/write operations, using buffered streams makes I/O more efficient. Java provides:

  • BufferedReader – for reading text efficiently
  • BufferedWriter – for writing text efficiently

These classes use a buffer to reduce the number of I/O operations, improving performance.

A. BufferedReader – Efficient Character Reading

BufferedReader reads text from a character-input stream and buffers characters for efficient reading of characters, arrays, or lines.

✅ Syntax:

BufferedReader reader = new BufferedReader(new FileReader("file.txt"));

✅ Common Methods:

  • readLine() – Reads one line at a time.
  • read() – Reads one character at a time.
  • close() – Closes the stream.

✅ Example:

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

public class BufferedReaderExample {
    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader("notes.txt"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

✅ Explanation:

  • readLine() reads a full line until a newline character.
  • More efficient than reading one character at a time with FileReader.

B. BufferedWriter – Efficient Character Writing

BufferedWriter writes text to a character-output stream and buffers the characters to improve performance.

✅ Syntax:

BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));

✅ Common Methods:

  • write(String s) – Writes a string.
  • newLine() – Writes a line separator.
  • close() – Closes the stream.

✅ Example:

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

public class BufferedWriterExample {
    public static void main(String[] args) {
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter("notes.txt"));
            writer.write("BufferedWriter makes writing efficient.");
            writer.newLine();
            writer.write("It writes a line at a time.");
            writer.close();
            System.out.println("Data written successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

✅ Explanation:

  • newLine() is platform-independent and inserts a proper line break.
  • BufferedWriter is preferred over FileWriter when writing large amounts of data.

✅ Comparison Table

FeatureBufferedReaderBufferedWriter
PurposeEfficient character readingEfficient character writing
Buffer Size8192 characters (default)8192 characters (default)
Key MethodsreadLine(), read()write(), newLine(), flush()
PerformanceFaster than FileReaderFaster than FileWriter

 

8. Byte Stream I/O (FileInputStream & FileOutputStream)

Java provides byte stream classes to perform input and output of raw binary data, such as images, audio, video, and any file that is not plain text. The two most commonly used byte stream classes are:

  • FileInputStream – for reading bytes from a file
  • FileOutputStream – for writing bytes to a file

These classes belong to the java.io package.

A. FileInputStream – Reading Bytes

This class is used to read raw byte data from a file.

✅ Syntax:

FileInputStream input = new FileInputStream("file.dat");

✅ Common Methods:

  • read() – Reads one byte at a time and returns it as an integer
  • read(byte[] b) – Reads multiple bytes into an array
  • close() – Closes the input stream

✅ Example:

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

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

✅ Explanation:

  • read() returns the next byte (0-255). -1 indicates the end of the file.
  • Binary data can be cast to char for text display (if it’s text data).

B. FileOutputStream – Writing Bytes

This class is used to write raw byte data to a file.

✅ Syntax:

FileOutputStream output = new FileOutputStream("file.dat");

✅ Common Methods:

  • write(int b) – Writes one byte
  • write(byte[] b) – Writes an array of bytes
  • close() – Closes the output stream

✅ Example:

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

public class FileOutputStreamExample {
    public static void main(String[] args) {
        try {
            FileOutputStream output = new FileOutputStream("data.bin");
            String data = "Binary Output Example";
            output.write(data.getBytes()); // Convert string to byte array
            output.close();
            System.out.println("Data written successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

✅ Explanation:

  • getBytes() converts a string to a byte array.
  • Suitable for saving binary or character data in a byte-based format.

✅ Summary Table

FeatureFileInputStreamFileOutputStream
PurposeRead raw byte dataWrite raw byte data
Use CaseReading binary files (images, etc.)Writing binary files
Key Methodsread(), read(byte[]), close()write(int), write(byte[]), close()
Data TypeByte-based (binary)Byte-based (binary)

9. Scanner vs BufferedReader – Input Comparison in Java

Both Scanner and BufferedReader are used to read input from users or files, but they differ in syntax, performance, flexibility, and use cases. Understanding the differences helps you choose the right one based on your application.

A. Scanner Class

Scanner is a utility class introduced in Java 5. It provides methods to read input from various sources, including keyboard input, files, and streams. It is easy to use, especially for beginners.

✅ Syntax for reading user input:

import java.util.Scanner;

Scanner sc = new Scanner(System.in);

✅ Example:

import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter name: ");
        String name = sc.nextLine();

        System.out.print("Enter age: ");
        int age = sc.nextInt();

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

✅ Key Methods:

  • next(), nextLine() – Reads strings
  • nextInt(), nextDouble() – Reads numbers
  • hasNext(), hasNextInt() – Check availability

✅ Pros:

  • Simple syntax
  • Built-in parsing for different data types
  • Easy to use for console input

✅ Cons:

  • Slower than BufferedReader for large input
  • Mixing next() and nextLine() can be tricky (newline issue)

B. BufferedReader Class

BufferedReader is a more traditional way of reading character input. It is faster and more efficient than Scanner when working with large input or files.

✅ Syntax:

import java.io.BufferedReader;
import java.io.InputStreamReader;

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

✅ Example:

import java.io.*;

public class BufferedReaderExample {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(
                                  new InputStreamReader(System.in));

        System.out.print("Enter name: ");
        String name = reader.readLine();

        System.out.print("Enter age: ");
        int age = Integer.parseInt(reader.readLine());

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

✅ Key Methods:

  • readLine() – Reads a line of input as a string
  • Manual parsing required for numbers (e.g., Integer.parseInt())

✅ Pros:

  • Faster for large input
  • Efficient for file reading
  • Cleaner for line-by-line reading

✅ Cons:

  • Requires exception handling (IOException)
  • Manual parsing for non-string input

Here’s a short summary of the full “Input/Output in Java” index:

Quick Summary

  1. Introduction to I/O
    Java I/O allows programs to take input and display output, using classes from the java.io package.
  2. Reading from Keyboard (Scanner)
    Scanner is used for easy console input. Supports reading strings, integers, and other data types directly.
  3. Reading from Keyboard (BufferedReader)
    BufferedReader reads text efficiently, line by line. Suitable for large input, needs manual parsing.
  4. Printing Output (System.out.print/println)
    Used to display output on the console. Supports formatted and simple printing.
  5. Writing Output (System.out.printf, PrintWriter)
    System.out.printf() enables formatted output. PrintWriter is used for writing formatted output to files or console.
  6. FileReader & FileWriter (Character I/O)
    Used to read/write character-based files (.txt). Simple and effective for text files.
  7. BufferedReader & BufferedWriter (Efficient Character I/O)
    Buffered classes offer faster reading/writing by reducing I/O operations.
  8. FileInputStream & FileOutputStream (Byte Stream I/O)
    Used for reading and writing binary data (images, audio, etc.).
  9. Scanner vs BufferedReader
    Scanner is easy for user input, BufferedReader is better for performance and large data.

 

 

Next Blog- Inheritance in Java

 

Sanjiv
0

You must logged in to post comments.

Get In Touch

123 Street, New York, USA

+012 345 67890

techiefreak87@gmail.com

© Design & Developed by HW Infotech