Input/Output: Exploring java.io, Directories (File Class) & Stream Classes
Overview: A directory entry tells you that a file exists, while a stream lets you read its contents.
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…
- 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).
The File Class and Working with Directories
- The
java.io.Fileclass 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! - 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.exists():booleangetName():StringgetAbsolutePath():Stringlength():long
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,…
-
- 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
Systemclass 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.
View diagram · Figure 5.1: Concept of Input Stream and Output Stream in Java
Classification of Java Stream Classes (Byte vs Character Streams)
- All stream classes in
java.ioare divided into two major hierarchies based on the type of data they handle: - 1. Byte Streams (8-Bit Raw Binary) Root Classes: InputStream & OutputStream
- 2. Character Streams (16-Bit Unicode Text) Root Classes: Reader & Writer
- 1. Data Unit: Operates on 8-bit bytes (1 byte at a time).
- 2. Abstract Root Classes:
InputStream(for reading) andOutputStream(for writing). - 3. Naming Convention: Class names always end with
InputStreamorOutputStream. - 4. Best Used For: Binary files: Images (
.jpg,.png), MP3 audio, videos,.classfiles,.zip. - 5. Core File Classes:
FileInputStreamandFileOutputStream.
View diagram · Figure 5.2: Hierarchy of Java I/O Stream Classes (java.io)
The Byte Stream: InputStream, OutputStream, File I/O, PrintStream & RandomAccessFile
Overview: A byte stream can copy an image without interpreting its bytes as text.
Abstract Superclasses of Byte Streams: InputStream & OutputStream
- All byte stream classes in
java.iodescend from two abstract superclasses that handle 8-bit raw bytes: - A. InputStream (Abstract Root Class for Reading Bytes): Defines the fundamental methods that every byte input stream must implement:
int read(): Reads the next single byte of data from the input stream (returns anintbetween0and255), or returns-1…int read(byte[] b): Reads a chunk of bytes into the byte arrayband returns the number of bytes actually read.int available(): Returns the number of bytes currently available for reading without blocking.void close(): Closes the input stream and releases any OS file locks.- B. OutputStream (Abstract Root Class for Writing Bytes): Defines the fundamental methods that every byte output stream must implement:
void write(int b): Writes a single byte to the output stream.
FileInputStream and FileOutputStream
- These are the two most commonly used concrete byte stream classes for reading from and writing to actual files on your computer’s hard disk.
- A. FileOutputStream (Writing Bytes to a File): Used to create a file and write raw byte data into it.
- If the specified file does not exist on disk,
FileOutputStreamautomatically creates a new file! - Constructors:
FileOutputStream fos = new FileOutputStream("data.txt");(Overwrites existing file)FileOutputStream fos = new FileOutputStream("data.txt", true);(Appends to the end of the file becauseappend = true)- B. FileInputStream (Reading Bytes from a File): Used to read raw bytes from an existing file on disk (such as a text file, image, or audio file).
- Throws
FileNotFoundExceptionif the file does not exist.
The PrintStream Class
- Have you ever wondered how
System.out.println()works? - What is
PrintStream?PrintStreamis a byte output stream (subclass ofFilterOutputStream) that adds convenient methods to print **any data… - 2 Unique Features of
PrintStream: - Never Throws
IOException! Unlike other streams,PrintStreamcatchesIOExceptioninternally and sets an internal error flag that can be checked via… - Auto-Flushing: Can be configured to flush the output buffer automatically whenever a newline character (
\n) is written. - Key Methods:
print(),println(),printf(),format(),checkError().
RandomAccessFile in Java
- All standard streams (
FileInputStream,FileOutputStream,FileReader) are Sequential Access Streams—meaning you must start at byte0… - Key Features of RandomAccessFile: Supports Both Reading and Writing: Implements both
DataInputandDataOutputinterfaces in a single class! - Movable File Pointer (
seek): Maintains an internal cursor called the File Pointer (like the cursor in Notepad) that you can move forward or backward… - Access Modes in Constructor (
new RandomAccessFile(file, mode)): "r"(Read-Only): Opens the file for reading only."rw"(Read and Write): Opens the file for both reading and writing (creates the file if it doesn’t exist).- Important Methods of RandomAccessFile:
void seek(long pos): Moves the file-pointer offset to byte positionposfrom the beginning of the file. long getFilePointer(): Returns the current byte offset location of the file pointer.
View diagram · Figure 5.3: Sequential Stream vs RandomAccessFile (seek() Pointer)
Character Streams, BufferedReader, BufferedWriter, PrintWriter & Serialization
Overview: A reader decodes bytes into characters using an encoding.
The Character Streams (Reader and Writer)
- While Byte Streams (
InputStream/OutputStream) read and write 8-bit raw bytes, Character Streams are designed specifically for reading… - Abstract Root Classes of Character Streams:
java.io.Reader(For Reading Characters): int read(): Reads a single character (returns-1at End of File).int read(char[] cbuf): Reads characters into achararray.void close(): Closes the stream.- Concrete File Subclass:
FileReader(new FileReader("notes.txt")). java.io.Writer(For Writing Characters):void write(int c): Writes a single character.
BufferedReader and BufferedWriter (High-Speed Buffered Text I/O)
- Reading or writing a file one single character at a time directly from the hard disk (
FileReader/FileWriter) is slow because every… - A. BufferedReader: Wraps around any
Reader(likeFileReaderorInputStreamReader) to buffer input and provide the super-usefulreadLine()method! - Star Method —
String readLine(): Reads an entire line of text at once and returns it as aString(returnsnullwhen the End of File is reached). - B. BufferedWriter: Wraps around any
Writer(likeFileWriter) to buffer characters in RAM before writing them in bulk to the disk. - Star Method —
void newLine(): Writes a platform-independent line separator (\r\non Windows,\non Linux/Mac).
View diagram · Figure 5.4: How BufferedReader Speeds Up File Reading Using a RAM Buffer
The PrintWriter Class
PrintWriteris the Character-Stream equivalent ofPrintStream!- Just like
PrintStream,PrintWriterprovides convenientprint(),println(), andprintf()methods for all primitive… - Why is
PrintWriterpreferred overPrintStreamfor text files? BecausePrintWriteris a Character Stream (Writer) that properly supports 16-bit Unicode characters and…
Serialization in Java (Saving & Restoring Objects)
- Normally, when your Java program terminates, all objects living in Heap memory are wiped out.
- Serialization: The process of converting the state of a live Java Object into a linear sequence of bytes (Byte Stream) so that it can…
- Deserialization: The reverse process of reconstructing the live Java Object in memory from the saved Byte Stream.
- Key Components of Serialization:
java.io.SerializableInterface (Marker Interface): - A class MUST implement the
Serializableinterface to allow its objects to be serialized (class Student implements Serializable). - What is a Marker Interface? An empty interface with zero methods!
ObjectOutputStream&writeObject(Object obj):ObjectInputStream&readObject():
View diagram · Figure 5.5: Object Serialization and Deserialization in Java
JDBC: JDBC-ODBC Bridge, Connectivity Model, DriverManager & java.sql Package
Overview: JDBC gives Java code a common way to request a connection and issue SQL.
What is JDBC (Java Database Connectivity)?
- JDBC is a standard Java API (Application Programming Interface) provided in the
java.sqlpackage that enables a Java program to… - Why do we need JDBC?
- Every database vendor (Oracle, MySQL, Microsoft) writes their database server using different internal protocols.
The JDBC Connectivity Model (Architecture)
- The JDBC Connectivity Model defines how a Java application communicates with a database through two layers:
- JDBC API Layer (
java.sql): Provides application-to-JDBC Manager communication (used by the Java programmer). - JDBC Driver API Layer: Supports JDBC Manager-to-Driver communication (implemented by database vendors like MySQL or Oracle).
- Two-Tier vs Three-Tier Connectivity Models: Two-Tier Model (Client-Server): The Java application (Client) talks directly to the Database Server using a JDBC Driver.
- Three-Tier Model (Web/Enterprise): The Client browser talks to an Application Server (Middle Tier) running Java, which in turn uses JDBC to talk to the…
View diagram · Figure 5.6: The JDBC Connectivity Model (Architecture)
JDBC-ODBC Bridge & The 4 Types of JDBC Drivers
- To connect a Java application to a database, we need a JDBC Driver.
- Type-1 Driver: The JDBC-ODBC Bridge Driver (sun.jdbc.odbc.JdbcOdbcDriver): How it Works: In the early days of Java, Microsoft’s ODBC (Open Database Connectivity) was already widely installed on Windows…
- Advantages of JDBC-ODBC Bridge:
- Allows Java to connect to almost any database (like MS Access or Excel) for which an ODBC driver is installed on the computer.
- Disadvantages of JDBC-ODBC Bridge:
- Platform Dependent: Requires native C/C++ ODBC drivers and a DSN (Data Source Name) configured on the client OS.
- Slow Performance: Every SQL query must undergo two translations (Java JDBC → C ODBC → Native DB protocol).
- (Removed in Java 8+ in favor of Type-4 Pure Java Drivers).
View diagram · Figure 5.7: How the Type-1 JDBC-ODBC Bridge Driver Works
The DriverManager Class
java.sql.DriverManageris the central management class of JDBC that sits between the Java application and the registered JDBC Drivers.- Role of
DriverManager: It maintains a list of all loadedDriverclasses. - Key Static Methods of DriverManager:
static Connection getConnection(String url, String user, String password): static void registerDriver(Driver driver):static void setLoginTimeout(int seconds):
Exploring the java.sql Package (Core Interfaces & Classes)
- The
java.sqlpackage contains the core interfaces and classes that every BCA student uses in JDBC programs: - 1.
DriverManager: Class - 2.
Connection: Interface - 3.
Statement: Interface - 4.
PreparedStatement: Interface - 5.
CallableStatement: Interface - 6.
ResultSet: Interface