Chapter 13
Java I/O & File Handling
4 topics · 1 sections · beginner-friendly study notes · Updated
Java I/O moves data between your program and files, the console or the network using streams.
This chapter covers file handling, byte streams vs character streams, buffered readers/writers and object serialization.
Almost every real application reads configuration, writes logs, saves data or exchanges files.
File handling and serialization are staple viva and interview topics.
Reading CSV and log files, saving user data, copying images, caching objects, sending objects between JVMs.
File Handling in Java
File handling is creating, reading, writing, copying, moving, listing and deleting files and directories from Java code, using java.io.File (path and metadata), java.io streams, and the modern java.nio.file API (Path, Paths, Files).
In short: Java can open a file like a notebook: check whether it exists, write lines in it, read them back and delete it.
Think about it
Persistent data lives in files; a program that cannot handle them cannot save results, read input or write logs. A filing cabinet: the File object is the label on a drawer; streams are the hands that open the drawer and read or write papers.
The File class represents a pathname, not the content: exists(), isFile(), isDirectory(), `length(), getName(), getParent(), getAbsolutePath(), createNewFile(), mkdir()/mkdirs(), list()/listFiles(), delete(), renameTo()`.
To read or write content use streams/readers/writers or the NIO.
2 Files helpers (Java 7+; some added in 11): `Files.
readAllLines, Files.
lines` (lazy stream), `Files.
readString, Files.
writeString, Files.
write, Files.
copy, Files.
move, Files.
delete, Files.
createTempFile, Files.
walk`.
File separators differ per OS, so use `File.
separator or Paths.
get("a", "b")`.
Most operations throw IOException (checked), so wrap them in try/catch or declare throws.
FileWriter overwrites by default; pass true to append.
Always close resources (try-with-resources) and specify the charset (StandardCharsets.
UTF_8) for portable text.
Scanner can parse a file token by token.
Key points
- File: Abstract representation of a file or directory path.
- Path / Files: NIO.2 classes for path handling and file operations.
- IOException: Checked exception for I/O failures.
- Append mode: Writing at the end of a file without erasing it.
- File does not read content; it describes a path.
FileWriter(file)overwrites;FileWriter(file, true)appends.- Use try-with-resources so streams close even on errors.
- Prefer Files and Path for new code.
Example
CodeCreate, write, read, append and delete a file:
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
public class FileDemo {
public static void main(String[] args) {
try {
Path p = Files.createTempFile("demo", ".txt");
Files.write(p, "Hello\nJava\n".getBytes(StandardCharsets.UTF_8));
File f = p.toFile();
System.out.println(f.exists() + " " + f.isFile()); // true true
System.out.println(f.getName().endsWith(".txt")); // true
System.out.println(f.length()); // 11 (5+1+4+1 bytes)
List<String> lines = Files.readAllLines(p);
System.out.println(lines); // [Hello, Java]
try (FileWriter fw = new FileWriter(f, true)) { // append mode
fw.write("More\n");
}
System.out.println(Files.readAllLines(p).size()); // 3
try (Scanner sc = new Scanner(f)) {
while (sc.hasNextLine()) System.out.print(sc.nextLine() + ";"); // Hello;Java;More;
}
System.out.println();
System.out.println(f.delete()); // true
System.out.println(f.exists()); // false
new FileReader("does-not-exist.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found"); // File not found
} catch (IOException e) {
System.out.println("I/O error: " + e.getMessage());
}
File dir = new File(".");
String[] names = dir.list();
System.out.println(names != null); // true
}
}Byte Stream vs Character Stream
Byte streams (InputStream / OutputStream and subclasses such as FileInputStream and FileOutputStream) read and write raw 8-bit bytes. Character streams (Reader / Writer and subclasses such as FileReader and FileWriter) read and write 16-bit Unicode characters and handle character encoding.
In short: Use byte streams for anything (images, PDFs, zip). Use character streams when the file is human-readable text.
Think about it
Picking the wrong stream type corrupts files or garbles text, and the difference is a classic viva question. Bytes are raw Lego bricks; characters are finished words built from bricks using an agreed alphabet (encoding).
InputStream.
read() returns an int 0–255 or -1 at end of stream; Reader.
read() returns a char code or -1.
Byte streams are the base abstraction: all data on disk is bytes.
Character streams add the decoding step bytes → chars using a charset (UTF-8, ISO-8859-1...
), which matters for non-ASCII text: "h\u00e9llo" has 5 chars but 6 bytes in UTF-8.
The bridge classes InputStreamReader and OutputStreamWriter convert from byte streams to character streams with an explicit charset.
System.
in is an InputStream (bytes), System.
out is a PrintStream.
Processing a binary file with a Reader corrupts it because bytes are interpreted as text.
Useful wrappers (decorator pattern): BufferedInputStream/BufferedOutputStream, DataInputStream/DataOutputStream (primitives), ObjectInputStream/ObjectOutputStream, PrintWriter.
Remember to close them or use try-with-resources.
Key points
- InputStream / OutputStream: Abstract base classes for byte input/output.
- Reader / Writer: Abstract base classes for character input/output.
- Charset: Mapping between characters and bytes (UTF-8, ASCII, ISO-8859-1).
- Bridge class: InputStreamReader / OutputStreamWriter: bytes ↔ characters.
- Byte: 8-bit, binary data, ends with InputStream/OutputStream.
- Character: 16-bit Unicode, text data, ends with Reader/Writer.
read()returns -1 at end of data.- Use
InputStreamReader(System.in)to read characters from the keyboard.
Example
CodeByte streams, character streams and the bridge classes:
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
public class StreamsDemo {
public static void main(String[] args) throws IOException {
File bin = File.createTempFile("bytes", ".bin");
File txt = File.createTempFile("chars", ".txt");
// Byte stream: write and read raw bytes
try (FileOutputStream out = new FileOutputStream(bin)) {
out.write(65); // 'A'
out.write("BC".getBytes()); // 66, 67
}
try (FileInputStream in = new FileInputStream(bin)) {
int b;
while ((b = in.read()) != -1) System.out.print(b + " "); // 65 66 67
System.out.println();
}
// Character stream: write and read text
try (Writer w = new FileWriter(txt)) {
w.write("Java I/O");
}
try (Reader r = new FileReader(txt)) {
int ch;
StringBuilder sb = new StringBuilder();
while ((ch = r.read()) != -1) sb.append((char) ch);
System.out.println(sb); // Java I/O
}
// Chars vs bytes
String s = "h\u00e9llo";
System.out.println(s.length()); // 5 characters
System.out.println(s.getBytes(StandardCharsets.UTF_8).length); // 6 bytes
System.out.println(s.getBytes(StandardCharsets.ISO_8859_1).length); // 5 bytes
// Bridge: bytes -> characters with a charset
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(txt), StandardCharsets.UTF_8))) {
System.out.println(br.readLine()); // Java I/O
}
// Copy any file (works for images too) using bytes
File copy = File.createTempFile("copy", ".bin");
try (InputStream in = new FileInputStream(bin);
OutputStream out = new FileOutputStream(copy)) {
byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) > 0) out.write(buf, 0, n);
}
System.out.println(copy.length()); // 3
bin.delete(); txt.delete(); copy.delete();
}
}BufferedReader and BufferedWriter
BufferedReader and BufferedWriter wrap another Reader or Writer and add an in-memory buffer (8192 characters by default), so data is moved in large chunks instead of one character at a time. BufferedReader adds readLine(); BufferedWriter adds newLine().
In short: Instead of walking to the file for every letter, the buffer carries a whole bucket of text at once.
Think about it
Buffering makes text I/O much faster and gives convenient line-based reading. Carrying water with a bucket instead of a spoon.
Every read/write on an unbuffered FileReader or FileWriter can trigger a slow operating-system call.
A buffer reduces the number of calls dramatically.
`BufferedReader.
readLine() returns one line without the line terminator and null at end of file; lines()` returns a Stream<String>.
`BufferedWriter.
write(String) stores data in the buffer; newLine() writes the platform line separator; flush() pushes buffered data to the destination; close()` flushes and closes the underlying stream (the file may be incomplete if you forget).
Typical construction: new BufferedReader(new FileReader(file)) or, for the console, `new BufferedReader(new InputStreamReader(System.
in))`.
Both are best used with try-with-resources.
`Files.
newBufferedReader(path) / newBufferedWriter(path)` give buffered streams with a charset.
For simple tokens Scanner is more convenient but slower; BufferedReader is preferred for large input (competitive programming) and files.
Key points
- Buffer: Temporary memory area that batches I/O.
readLine(): Reads a line; returnsnullat end of stream.newLine(): Writes the OS-specific line separator.flush(): Forces buffered data to be written out.- Default buffer size is 8192 characters.
readLine()returnsnull(not an empty string) at end of file.close()also flushes the buffer.- Wrap:
BufferedReader(new FileReader(...));BufferedWriter(new FileWriter(...)).
Read more
Example
CodeWriting and reading lines with buffers:
import java.io.*;
public class BufferedDemo {
public static void main(String[] args) throws IOException {
File f = File.createTempFile("notes", ".txt");
try (BufferedWriter bw = new BufferedWriter(new FileWriter(f))) {
bw.write("Java is fun");
bw.newLine();
bw.write("I love streams");
bw.newLine();
bw.write("Files are easy");
} // close() flushes automatically
int lines = 0, words = 0;
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
String line;
while ((line = br.readLine()) != null) { // null means end of file
lines++;
words += line.split(" ").length;
System.out.println(lines + ": " + line.toUpperCase());
}
}
// 1: JAVA IS FUN
// 2: I LOVE STREAMS
// 3: FILES ARE EASY
System.out.println(lines + " lines, " + words + " words"); // 3 lines, 9 words
// Reading keyboard input (console) - blocks until the user types a line:
// BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
// String name = console.readLine();
// Lazy stream of lines
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
System.out.println(br.lines().filter(l -> l.contains("e")).count()); // 2
}
f.delete();
}
}Serialization in Java
Serialization converts the state of an object into a byte stream so that it can be saved to a file, sent over a network or stored; deserialization rebuilds the object from that byte stream. A class opts in by implementing the marker interface java.io.Serializable.
In short: Serialization is freezing an object into bytes; deserialization is thawing it back into a living object.
Think about it
It is the built-in way to persist or transfer object graphs, and transient / serialVersionUID are standard interview questions. Packing a flat-pack wardrobe in a box (serialize) and assembling it again at home (deserialize); the transient screws you chose not to pack are missing afterwards.
Use `ObjectOutputStream.
writeObject(obj) and ObjectInputStream.
readObject()` (needs a cast and can throw ClassNotFoundException).
All fields are saved except transient fields (restored to defaults: null, 0, false) and `static` fields (belong to the class, not the object).
Every non-transient field must itself be Serializable, otherwise NotSerializableException is thrown.
`serialVersionUID` is a version number: if the class changes and the id differs, deserialization throws InvalidClassException; declare `private static final long serialVersionUID = 1L;` explicitly.
If a parent class is not Serializable, its no-argument constructor runs during deserialization and its fields are re-initialised.
Constructors of the serializable class are NOT called.
Customise with writeObject/readObject or Externalizable.
Singletons need readResolve.
Deserializing untrusted data is a security risk (remote code execution), so avoid native Java serialization for external input and prefer JSON for data exchange.
Key points
- Serializable: Marker interface (no methods) that allows serialization.
- transient: Field modifier that excludes the field from serialization.
- serialVersionUID: Version id used to verify compatible class versions.
- ObjectOutputStream / ObjectInputStream: Streams that write and read objects.
- transient and static fields are not serialized.
- Constructor of a Serializable class is not called on deserialization.
- Each referenced object must be Serializable too.
- Declare serialVersionUID explicitly.
Example
CodeSerialize and deserialize an object:
import java.io.*;
class User implements Serializable {
private static final long serialVersionUID = 1L;
String name;
int age;
transient String password; // not saved
static String company = "ACME"; // not saved (class-level)
User(String name, int age, String password) {
this.name = name;
this.age = age;
this.password = password;
System.out.println("constructor called");
}
}
public class SerializationDemo {
public static void main(String[] args) throws IOException, ClassNotFoundException {
User u = new User("Amit", 20, "secret"); // constructor called
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(bytes)) {
oos.writeObject(u); // serialize
}
System.out.println("Serialized bytes > 0: " + (bytes.size() > 0)); // true
User.company = "CHANGED";
try (ObjectInputStream ois =
new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
User copy = (User) ois.readObject(); // no "constructor called" printed
System.out.println(copy.name + " " + copy.age); // Amit 20
System.out.println(copy.password); // null (transient)
System.out.println(User.company); // CHANGED (static is not part of the object)
System.out.println(copy == u); // false (a new object)
}
}
}Solved examples
Write the lines "A" and "B" to a file and read them back with buffered classes.
Code outline
Formula Applied:—Approach note: The loop condition is readLine() != null, not an empty string check.
Which stream type should you use to copy a JPEG image: FileReader or FileInputStream?
Choice with reason
Formula Applied:—Approach note: Text → Reader/Writer; everything else → InputStream/OutputStream.
A User object has fields name, age and transient password. After serialization and deserialization, what are the field values?
Values after restore
Formula Applied:—Approach note: Primitive transient fields come back as 0 / false.
Using Files.writeString (Java 11+) write "hi" to path data.txt, then read it back with Files.readString. What is the round-trip result?
Content read
Formula Applied:—Approach note: Prefer java.nio.file.Files for simple whole-file read/write.
Real-world applications
Using Java I/O & File Handling in real projects
Reading CSV and log files, saving user data, copying images, caching objects, sending objects between JVMs.
Common mistakes
❌ Myth: A File object contains the file content.
Why this is wrong: File only represents a path and metadata.
✅ Verified Truth: Use streams, readers or Files.readAllLines to access the content.
⚠️ Exam Tip: new File("x.txt") does not create the file on disk.
❌ Myth: FileWriter appends to the file by default.
Why this is wrong: The default mode overwrites existing content.
✅ Verified Truth: Use new FileWriter(file, true) to append.
⚠️ Exam Tip: Common lab error.
❌ Myth: Serialization calls the constructor of the object.
Why this is wrong: The object is rebuilt directly from the stream.
✅ Verified Truth: Only the no-arg constructor of the first non-serializable parent runs.
⚠️ Exam Tip: Constructor print statements prove it.
❌ Myth: static fields are saved in serialization.
Why this is wrong: Static fields belong to the class.
✅ Verified Truth: Only instance state is serialized.
⚠️ Exam Tip: transient and static are skipped.
Revision notes
Java I/O moves data between your program and files, the console or the network using streams. This chapter covers file handling, byte streams vs character streams, buffered readers/writers and object serialization.
High-Yield Quick Revision Points
- File = path + metadata; use streams or Files for content
- Byte streams: InputStream/OutputStream; character: Reader/Writer
- Buffered classes batch I/O; readLine() null = EOF; close() flushes
- FileWriter(f, true) appends; always use try-with-resources
- Serializable marker; transient/static skipped; declare serialVersionUID
- Deserialization does not call the class constructor
Practice questions
Which class is a byte stream?
What does BufferedReader.readLine() return at end of file?
Which modifier excludes a field from serialization?
Which interface must a class implement to be serialized?
new FileWriter("a.txt", true) opens the file in:
Which class converts a byte stream to a character stream?