Reading and Writing Files in Java
Detailed Overview of File I/O with
FileInputStream and
FileOutputStream
Introduction to File I/O
• • Java supports file input/output through
stream classes.
• • Streams represent a connection to data
source/destination.
• • Two primary categories: Byte Streams and
Character Streams.
• • Focus: Byte Streams (FileInputStream,
FileOutputStream).
FileInputStream and
FileOutputStream
• • FileInputStream(String fileName): Opens file
for reading.
• → Throws FileNotFoundException if file does
not exist.
• • FileOutputStream(String fileName):
Opens/creates file for writing.
• → Destroys any pre-existing file with the
same name.
• • Both extend java.io classes and work with
bytes.
Exceptions in File I/O
• • FileNotFoundException: Raised if file not
found/opened.
• • IOException: General I/O failures (read/write
errors).
• • SecurityException: Triggered if security
manager restricts access.
• • Best practice: Always handle exceptions
explicitly.
Closing Files Properly
• • close() method: Releases system resources
tied to file.
• • Failure to close can cause memory leaks.
• • Two approaches:
• 1. Traditional: Explicitly call close() in code.
• 2. try-with-resources (JDK 7+): Automatically
closes files.
• • finally block ensures closure even if
exceptions occur.
Reading from Files
• • Method: int read() throws IOException.
• → Reads one byte at a time and returns it as
int.
• → Returns -1 when end of file is reached.
• • Used to read text or binary data.
• • Example: Display contents of ASCII text file.
Writing to Files
• • Method: void write(int byteVal) throws
IOException.
• → Writes low-order 8 bits of byteVal to file.
• • Errors while writing raise IOException.
• • Common use: Copying data from one file to
another.
Using finally Block for Closing
• • Recommended to close file inside a finally
block.
• • Ensures closure regardless of how try block
terminates.
• • Example pattern:
• FileInputStream fin = null;
• try { ... file access ... }
• finally { if(fin != null) fin.close(); }
Compact Exception Handling
• • FileNotFoundException is a subclass of
IOException.
• • Therefore, can catch IOException directly.
• • Compact style:
• try { ... file operations ... }
• catch(IOException e)
{ System.out.println(e); }
• • Useful when separate handling is not
required.
Advantages of Exceptions in File
I/O
• • Cleaner than error codes.
• • Separates normal flow from error handling.
• • End-of-file condition is not treated as error.
• • Allows propagating errors to calling routines
when needed.
Summary
• • Java provides FileInputStream and
FileOutputStream for byte-based file I/O.
• • Always handle exceptions:
FileNotFoundException, IOException,
SecurityException.
• • Closing files is mandatory: use close(), try-
with-resources, or finally block.
• • read() and write() methods handle basic
operations.
• • Exceptions make file handling structured and