←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Notes

Input/Output: Exploring java.io, Directories (File Class) & Stream Classes

Study material and explanations for Unit 5

Input/Output: Exploring java.io, Directories (File Class) & Stream Classes

1. Exploring the java.io Package

Almost every real-world program needs to read input data (from a keyboard, a disk file, or a network socket) and write output data (to the screen, a file, or a printer).

Java performs all Input and Output (I/O) operations through the java.io package, which contains over 50 classes and interfaces for:

  1. Inspecting and managing Files and Directories on the hard disk (File class).
  2. Reading and writing raw binary data using Byte Streams (InputStream, OutputStream).
  3. Reading and writing 16-bit Unicode text using Character Streams (Reader, Writer).
  4. Saving and restoring complete Java objects using Object Serialization (Serializable).

2. The File Class and Working with Directories

The java.io.File class is an abstract representation of file and directory (folder) pathnames on your computer’s hard disk.

  • Important Exam Fact: Creating a File object (File f = new File("notes.txt");) does NOT read or write data inside the file! Instead, the File class is used to query metadata/properties of a file or directory (such as checking if it exists, finding its size in bytes, renaming/deleting it, or listing all files inside a folder).

Constructors of the File Class:

  1. File f1 = new File("C:/BCA/notes.txt"); — Points to a specific file or directory path.
  2. File f2 = new File("C:/BCA", "syllabus.pdf"); — Specifies parent directory path and child filename separately.

Essential Methods of the File Class:

Method Return Type Description
exists() boolean Returns true if the file or directory actually exists on the disk.
getName() String Returns the name of the file or folder ("notes.txt").
getAbsolutePath() String Returns the complete path starting from C:\.
length() long Returns the size of the file in bytes.
canRead() / canWrite() boolean Checks if the file is readable or writable.
isFile() boolean Returns true if the path points to a normal file.
isDirectory() boolean Returns true if the path points to a Directory (Folder)!
mkdir() / mkdirs() boolean Creates a new directory (folder) on the disk.
list() String[] Returns an array of filenames inside a directory!
delete() boolean Deletes the file or empty directory from the disk.

Working with Directories in Java (Creating & Listing a Folder)

In Java, a Directory is simply a File object that contains a list of other files and subdirectories.

  1. To create a directory, create a File object and call mkdir() (creates a single folder) or mkdirs() (creates both parent and child folders).
  2. To list the contents of a directory, check if (dir.isDirectory()) and call String[] files = dir.list().
import java.io.File;

public class DirectoryDemo {
    public static void main(String[] args) {
        // 1. Create a new directory named "BCA_Notes"
        File newDir = new File("BCA_Notes");
        if (newDir.mkdir()) {
            System.out.println("Directory created: " + newDir.getAbsolutePath());
        }

        // 2. Inspect and list all files/folders inside the current directory (".")
        File currentDir = new File(".");
        if (currentDir.isDirectory()) {
            System.out.println("\nContents of Directory: " + currentDir.getAbsolutePath());
            String[] items = currentDir.list();

            for (int i = 0; i < items.length; i++) {
                File f = new File(currentDir, items[i]);
                if (f.isDirectory()) {
                    System.out.println("[DIR]  " + items[i]);
                } else {
                    System.out.println("[FILE] " + items[i] + " (" + f.length() + " bytes)");
                }
            }
        }
    }
}

3. What is a Stream in Java?

A Stream is a continuous, ordered flow (pipeline) of data between a Source (keyboard, file, network) and a Destination (screen, file, memory).

Simple Analogy: Think of a Water Pipe connecting an overhead tank to your kitchen tap:

  • Input Stream: Water flowing into your house (Reading data into your Java program from an external source).
  • Output Stream: Water flowing out of your house (Writing data out of your Java program to an external destination).
Figure 5.1: Concept of Input Stream and Output Stream in Java
Data SourceFile / Keyboard / Network
→ InputStream / Reader (Read) →
Java ProgramProcesses Data in RAM
→ OutputStream / Writer (Write) →
DestinationFile / Monitor / Socket

Standard Built-in Streams in java.lang.System:

Java automatically opens three ready-to-use streams inside the System class for every program:

  1. System.in (InputStream): Standard Input Stream — connected to the Keyboard by default.
  2. System.out (PrintStream): Standard Output Stream — connected to the Console Screen by default.
  3. System.err (PrintStream): Standard Error Stream — used to display error messages on the screen.

4. Classification of Java Stream Classes (Byte vs Character Streams)

All stream classes in java.io are divided into two major hierarchies based on the type of data they handle:

Figure 5.2: Hierarchy of Java I/O Stream Classes (java.io)
1. Byte Streams (8-Bit Raw Binary)
  • Root Classes: InputStream & OutputStream
  • Reads/writes data 1 byte (8 bits) at a time
  • Used for Images, Audio, Video, PDFs, & Binary files
  • Examples: FileInputStream, FileOutputStream, PrintStream, ObjectInputStream
2. Character Streams (16-Bit Unicode Text)
  • Root Classes: Reader & Writer
  • Reads/writes data 1 character (2 bytes / 16 bits) at a time
  • Automatically handles Unicode character encoding
  • Examples: FileReader, FileWriter, BufferedReader, BufferedWriter, PrintWriter

Comparison Table: Byte Streams vs Character Streams

Basis Byte Streams Character Streams
1. Data Unit Operates on 8-bit bytes (1 byte at a time). Operates on 16-bit Unicode characters (2 bytes at a time).
2. Abstract Root Classes InputStream (for reading) and OutputStream (for writing). Reader (for reading) and Writer (for writing).
3. Naming Convention Class names always end with InputStream or OutputStream. Class names always end with Reader or Writer.
4. Best Used For Binary files: Images (.jpg, .png), MP3 audio, videos, .class files, .zip. Plain text files: .txt, .csv, .html, .java, .json.
5. Core File Classes FileInputStream and FileOutputStream. FileReader and FileWriter.

💡 Exam Preparation Tips for DAVV BCA

  • Easy trick to identify any java.io class in the exam:
    • If the class name ends with Stream (FileInputStream, PrintStream), it is a Byte Stream.
    • If the class name ends with Reader or Writer (BufferedReader, PrintWriter), it is a Character Stream!
  • For questions on Directories, always write the File class methods isDirectory(), mkdir(), and list().