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:
- Inspecting and managing Files and Directories on the hard disk (
Fileclass). - Reading and writing raw binary data using Byte Streams (
InputStream,OutputStream). - Reading and writing 16-bit Unicode text using Character Streams (
Reader,Writer). - 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
Fileobject (File f = new File("notes.txt");) does NOT read or write data inside the file! Instead, theFileclass 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:
File f1 = new File("C:/BCA/notes.txt");— Points to a specific file or directory path.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.
- To create a directory, create a
Fileobject and callmkdir()(creates a single folder) ormkdirs()(creates both parent and child folders). - To list the contents of a directory, check
if (dir.isDirectory())and callString[] 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).
Standard Built-in Streams in java.lang.System:
Java automatically opens three ready-to-use streams inside the System class for every program:
System.in(InputStream): Standard Input Stream — connected to the Keyboard by default.System.out(PrintStream): Standard Output Stream — connected to the Console Screen by default.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:
- 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
- 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.ioclass in the exam:- If the class name ends with
Stream(FileInputStream,PrintStream), it is a Byte Stream. - If the class name ends with
ReaderorWriter(BufferedReader,PrintWriter), it is a Character Stream!
- If the class name ends with
- For questions on Directories, always write the
Fileclass methodsisDirectory(),mkdir(), andlist().