Reading and Writing Files in Java
Introduction to File I/O using
FileInputStream and
FileOutputStream
Introduction
• • Java provides classes and methods to
read/write files.
• • File I/O is a large topic (explored in detail
later).
• • Basic techniques use byte streams
(adaptable to character streams).
• • Commonly used classes: FileInputStream
and FileOutputStream.
FileInputStream and
FileOutputStream
• • FileInputStream(String fileName) throws
FileNotFoundException
• • FileOutputStream(String fileName) throws
FileNotFoundException
• • FileNotFoundException is a subclass of
IOException.
• • Opening an output file destroys preexisting
file with same name.
Security & Closing Files
• • SecurityException may occur if security
manager is present.
• • Always close files using close() method.
• • close() releases system resources.
• • Failure to close → memory leaks.
Approaches to Closing Files
• • Traditional approach: Explicitly call close().
• • try-with-resources (JDK 7+): Automatically
closes files.
• • finally block ensures closing, even if
exception occurs.
Reading from Files
• • int read() throws IOException
• • Reads one byte at a time.
• • Returns -1 at end of file.
• • Commonly used in simple file readers.
Writing to Files
• • void write(int byteval) throws IOException
• • Writes low-order 8 bits of byteval.
• • IOException if error occurs.
• • Used for copying files or writing output.
Exception Handling in File I/O
• • Java uses exceptions instead of error codes.
• • Differentiates between end-of-file and file
errors.
• • Can propagate exceptions or handle
explicitly.
• • Compact handling: catch IOException
instead of FileNotFoundException separately.