Language Features
File Handling
Complete lesson for File Handling using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — File Handling
Section: Language Features. Java file handling — create, write, read, append, copy, move, rename, and delete files with java.io and java.nio.file, plus every important file operation method in table format.
What is file handling?
- File handling means using a program to create, read, update, and delete files and folders on disk.
- Variables live in RAM and disappear when the program ends. Files keep data permanently (persistent storage).
- Java provides two APIs: the classic
java.iopackage (Java 1.0+) and the modernjava.nio.filepackage (NIO.2, Java 7+). - Real-life analogy: a notebook. You can open it, read pages, write new pages, add pages at the end (append), tear pages out (delete), or photocopy it (copy).
| Operation | Meaning | Classic java.io | Modern java.nio.file |
|---|---|---|---|
| Create | Make a new empty file or folder | file.createNewFile(), mkdir() | Files.createFile(p), createDirectories(p) |
| Write | Replace the content | FileWriter, BufferedWriter | Files.writeString(p, text) |
| Read | Get the content | FileReader, BufferedReader, Scanner | Files.readString(p), readAllLines(p) |
| Append | Add to the end | new FileWriter(f, true) | Files.writeString(p, t, APPEND) |
| Copy | Duplicate a file | Streams in a loop | Files.copy(src, dst) |
| Move / rename | Change location or name | file.renameTo(dest) | Files.move(src, dst) |
| Delete | Remove a file or empty folder | file.delete() | Files.delete(p), deleteIfExists(p) |
| Information | Size, dates, permissions | length(), lastModified() | Files.size(p), getLastModifiedTime(p) |
Differences between java.io.File and java.nio.file (Path / Files)
FileandPathonly describe a location. They do not hold content. Reading and writing is done by streams or theFilesutility class.- Prefer
Path+Filesfor new code. Usefile.toPath()andpath.toFile()to convert when an old API needsFile.
| Point | java.io.File | java.nio.file.Path + Files |
|---|---|---|
| Introduced | Java 1.0 | Java 7 (NIO.2) |
| Create a path | new File("a.txt") | Path.of("a.txt") (Java 11) or Paths.get("a.txt") |
| Error reporting | Returns false with no reason | Throws a specific exception (NoSuchFileException, ...) |
| Read whole file | Needs a stream and a loop | Files.readString, readAllLines, readAllBytes |
| Copy / move | No built-in copy; renameTo unreliable | Files.copy, Files.move with options |
| Symbolic links and attributes | Very limited | Full support (readAttributes, permissions) |
| Directory walking | listFiles() and manual recursion | Files.list, walk, find (Streams) |
| Recommended for new code | No (legacy) | Yes |
Byte streams vs character streams
- Byte streams (
InputStream/OutputStream) move raw 8-bit bytes: images, PDFs, ZIP, audio, any binary data. - Character streams (
Reader/Writer) move 16-bit characters and handle text encoding (UTF-8) for you. - Buffered wrappers (
BufferedReader,BufferedOutputStream, ...) read and write in large chunks, which is much faster than one byte at a time.
| Class | Type | Purpose | Key methods |
|---|---|---|---|
FileInputStream | Byte input | Read bytes from a file | read(), read(byte[]), readAllBytes() |
FileOutputStream | Byte output | Write bytes to a file | write(int), write(byte[]) |
BufferedInputStream / BufferedOutputStream | Byte, buffered | Faster binary I/O | Same as above plus flush() |
DataInputStream / DataOutputStream | Byte | Read / write primitives | readInt(), writeDouble(), readUTF() |
ObjectInputStream / ObjectOutputStream | Byte | Serialize whole objects | readObject(), writeObject() |
FileReader | Character input | Read text from a file | read(), read(char[]) |
FileWriter | Character output | Write text to a file | write(String), append() |
BufferedReader | Character, buffered | Read text line by line | readLine(), lines() |
BufferedWriter | Character, buffered | Write text efficiently | write(), newLine(), flush() |
PrintWriter | Character output | Formatted text output | println(), printf() |
Scanner | Text parser | Read tokens, numbers, lines | nextLine(), nextInt(), hasNext() |
RandomAccessFile | Both directions | Jump to any position | seek(), read(), write() |
java.io.File class methods
- Create an object with
File f = new File("data/notes.txt");. Creating the object does not create the file on disk.
| Method | Return type | Description |
|---|---|---|
createNewFile() | boolean | Creates an empty file; false if it already exists. Throws IOException |
exists() | boolean | Does the file or folder exist? |
isFile() / isDirectory() | boolean | Is it a regular file / a folder? |
getName() | String | File name only, such as notes.txt |
getPath() | String | Path as given to the constructor |
getAbsolutePath() | String | Full path from the drive or root |
getParent() | String | Parent folder path (or null) |
length() | long | Size in bytes (0 if missing) |
lastModified() | long | Last modified time in milliseconds since 1970 |
canRead() / canWrite() / canExecute() | boolean | Permission checks |
setReadOnly() / setWritable(b) | boolean | Change permissions |
delete() | boolean | Deletes a file or an empty folder |
deleteOnExit() | void | Deletes when the JVM exits (temporary files) |
mkdir() | boolean | Creates one folder (parent must exist) |
mkdirs() | boolean | Creates the folder and any missing parents |
renameTo(File dest) | boolean | Renames or moves; platform dependent |
list() | String[] | Names of entries in a folder |
listFiles() | File[] | Entries as File objects (null if not a folder) |
toPath() | Path | Convert to the NIO Path type |
java.nio.file.Files class methods
Filescontains onlystaticmethods. Every method that touches the disk throwsIOException.
| Category | Method | Description |
|---|---|---|
| Check | Files.exists(p) / notExists(p) | Does the path exist? |
| Check | Files.isRegularFile(p) / isDirectory(p) | File or folder? |
| Check | Files.isReadable(p) / isWritable(p) / isHidden(p) | Permission and visibility checks |
| Create | Files.createFile(p) | New empty file; throws FileAlreadyExistsException if present |
| Create | Files.createDirectory(p) / createDirectories(p) | One folder / folder with all parents |
| Create | Files.createTempFile(prefix, suffix) | Unique temporary file |
| Read | Files.readString(p) | Whole text file into one String (Java 11) |
| Read | Files.readAllLines(p) | All lines into a List<String> |
| Read | Files.readAllBytes(p) | Whole file into a byte[] |
| Read | Files.lines(p) | Lazy Stream<String> of lines; close it |
| Read | Files.newBufferedReader(p) | Opens a BufferedReader (UTF-8 by default) |
| Write | Files.writeString(p, text, options...) | Write a String (Java 11) |
| Write | Files.write(p, lines) / write(p, bytes) | Write a list of lines or a byte array |
| Write | Files.newBufferedWriter(p, options...) | Opens a BufferedWriter |
| Copy / move | Files.copy(src, dst, options...) | Copy a file; add REPLACE_EXISTING to overwrite |
| Copy / move | Files.move(src, dst, options...) | Move or rename; supports ATOMIC_MOVE |
| Delete | Files.delete(p) | Delete; throws NoSuchFileException if missing |
| Delete | Files.deleteIfExists(p) | Delete; returns false if missing |
| Info | Files.size(p) | Size in bytes |
| Info | Files.getLastModifiedTime(p) | Last modified time as FileTime |
| Info | Files.probeContentType(p) | Guess MIME type, such as text/plain |
| Directory | Files.list(dir) | Stream of direct children |
| Directory | Files.walk(dir) | Stream of every file and folder below dir |
| Directory | Files.find(dir, depth, matcher) | Search by name, size, or date |
| Compare | Files.mismatch(p1, p2) | Position of the first different byte, or -1 (Java 12) |
Path interface methods
| Method | Example | Result |
|---|---|---|
Path.of(first, more...) | Path.of("data", "notes.txt") | data/notes.txt with the OS separator |
getFileName() | p.getFileName() | notes.txt |
getParent() | p.getParent() | data |
getRoot() | p.toAbsolutePath().getRoot() | C: root on Windows, / on Linux |
toAbsolutePath() | p.toAbsolutePath() | Full path from the root |
resolve(other) | dir.resolve("a.txt") | Joins two paths |
resolveSibling(name) | p.resolveSibling("b.txt") | Same folder, different file name |
relativize(other) | base.relativize(full) | Relative path between two paths |
normalize() | Path.of("a/./b/../c").normalize() | a/c |
startsWith() / endsWith() | p.endsWith("notes.txt") | true (compares path parts, not text) |
toFile() | p.toFile() | Convert to java.io.File |
Reader, Writer, and stream methods
| Class | Method | Description |
|---|---|---|
FileWriter | new FileWriter(name) / new FileWriter(name, true) | Overwrite / append mode |
FileWriter, BufferedWriter | write(String) | Write text (no newline added) |
BufferedWriter | newLine() | Write the platform line separator |
| Any writer / output stream | flush() | Push buffered data to disk now |
| Any stream | close() | Flush and release the file handle (use try-with-resources) |
PrintWriter | println(), printf(), format() | Formatted text output |
FileReader | read() | One character as int; -1 at end of file |
BufferedReader | readLine() | One line without the newline; null at end of file |
BufferedReader | lines() | Stream of remaining lines |
Scanner | hasNextLine(), nextLine() | Line-by-line reading |
Scanner | hasNextInt(), nextInt(), next() | Token and number reading |
FileInputStream | read(), read(byte[] buf) | Byte / chunk reading; -1 at end of file |
FileInputStream | readAllBytes(), transferTo(out) | Read everything / copy to another stream (Java 9) |
FileOutputStream | write(byte[] buf, off, len) | Write part of a byte array |
StandardOpenOption values
- Pass these to
Files.writeString,Files.write, orFiles.newBufferedWriterto control how the file is opened.
| Option | Effect |
|---|---|
CREATE | Create the file if it does not exist |
CREATE_NEW | Create the file; fail if it already exists |
APPEND | Write at the end of the file |
TRUNCATE_EXISTING | Empty the file before writing (default with CREATE and WRITE) |
WRITE | Open for writing |
READ | Open for reading |
DELETE_ON_CLOSE | Delete the file when it is closed |
SYNC / DSYNC | Write every change straight to the storage device |
Create a file
File.createNewFile()returnsfalseif the file is already there.Files.createFile()throwsFileAlreadyExistsExceptioninstead, so you know exactly what happened.- Create parent folders first with
mkdirs()orFiles.createDirectories().
import java.io.File;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
public class CreateFile {
public static void main(String[] args) throws IOException {
// classic java.io
File f = new File("data/classic.txt");
f.getParentFile().mkdirs();
if (f.createNewFile()) System.out.println("Created " + f.getName());
else System.out.println(f.getName() + " already exists");
// modern java.nio.file
Path p = Path.of("data", "modern.txt");
Files.createDirectories(p.getParent());
try {
Files.createFile(p);
System.out.println("Created " + p.getFileName());
} catch (FileAlreadyExistsException e) {
System.out.println(p.getFileName() + " already exists");
}
}
} Write to a file
- Writing replaces the old content unless you choose append mode.
- Use
BufferedWriterorPrintWriterfor many small writes; useFiles.writeStringfor one shot. - Always pass
StandardCharsets.UTF_8(or rely on Java 18+ where UTF-8 is the default).
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class WriteFile {
public static void main(String[] args) throws IOException {
// 1. FileWriter + BufferedWriter
try (BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt", StandardCharsets.UTF_8))) {
bw.write("Line 1");
bw.newLine();
bw.write("Line 2");
}
// 2. PrintWriter for formatted output
try (PrintWriter pw = new PrintWriter("report.txt", StandardCharsets.UTF_8)) {
pw.printf("%-10s %5d%n", "Java", 95);
pw.printf("%-10s %5d%n", "Python", 88);
}
// 3. Files (one call)
Files.writeString(Path.of("b.txt"), "Hello from NIO", StandardCharsets.UTF_8);
Files.write(Path.of("c.txt"), List.of("red", "green", "blue"), StandardCharsets.UTF_8);
System.out.println("Files written");
}
} Read from a file
- Small files:
Files.readStringorFiles.readAllLines. - Large files:
BufferedReader.readLine()in a loop orFiles.linesso only one line is in memory at a time. Scanneris handy when the file contains numbers or tokens.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Stream;
public class ReadFile {
public static void main(String[] args) throws IOException {
// 1. BufferedReader line by line
try (BufferedReader br = new BufferedReader(new FileReader("a.txt", StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
// 2. Scanner
try (Scanner sc = new Scanner(new File("c.txt"), StandardCharsets.UTF_8)) {
while (sc.hasNextLine()) System.out.println(sc.nextLine());
}
// 3. Files: whole file, all lines, or a lazy stream
String all = Files.readString(Path.of("b.txt"));
List<String> lines = Files.readAllLines(Path.of("c.txt"));
try (Stream<String> s = Files.lines(Path.of("c.txt"))) {
System.out.println(s.filter(x -> x.startsWith("g")).count()); // 1
}
System.out.println(all + " / " + lines);
}
} Append to a file
- Pass
trueas the second argument ofFileWriter, or useStandardOpenOption.APPENDwithFiles. - Add
CREATEso the first append creates the file if it is missing.
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
public class AppendFile {
public static void main(String[] args) throws IOException {
try (FileWriter fw = new FileWriter("log.txt", true)) { // true = append
fw.write("Started at " + LocalDateTime.now() + System.lineSeparator());
}
Files.writeString(Path.of("log.txt"), "Second entry" + System.lineSeparator(),
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
System.out.print(Files.readString(Path.of("log.txt")));
}
} Copy, move, rename, and delete files
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class FileOps {
public static void main(String[] args) throws IOException {
Path src = Path.of("a.txt");
Path backup = Path.of("backup", "a-copy.txt");
Files.createDirectories(backup.getParent());
Files.copy(src, backup, StandardCopyOption.REPLACE_EXISTING); // copy
Path renamed = Files.move(backup, backup.resolveSibling("a-old.txt"),
StandardCopyOption.REPLACE_EXISTING); // rename
System.out.println("Renamed to " + renamed);
boolean removed = Files.deleteIfExists(renamed); // delete
System.out.println("Deleted: " + removed);
Files.delete(backup.getParent()); // folder must be empty
}
} Get file information
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class FileInfo {
public static void main(String[] args) throws IOException {
File f = new File("a.txt");
if (f.exists()) {
System.out.println("Name : " + f.getName());
System.out.println("Absolute : " + f.getAbsolutePath());
System.out.println("Size : " + f.length() + " bytes");
System.out.println("Readable : " + f.canRead());
System.out.println("Writable : " + f.canWrite());
}
Path p = Path.of("a.txt");
System.out.println("Is file : " + Files.isRegularFile(p));
System.out.println("Modified : " + Files.getLastModifiedTime(p));
System.out.println("Type : " + Files.probeContentType(p));
}
} try-with-resources
- Open every
AutoCloseableresource (Reader,Writer,InputStream,Scanneron a file,StreamfromFiles.lines) insidetry ( ... ). - Java calls
close()automatically at the end of the block, even if an exception is thrown. Resources close in reverse order of opening. - Without closing, data may stay in the buffer and never reach the disk, and on Windows the file stays locked.
- Do not swallow
IOException. Declarethrows IOExceptionin small programs, or catch it and show a helpful message.
import java.io.*;
public class CopyText {
public static void main(String[] args) {
try (BufferedReader in = new BufferedReader(new FileReader("a.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("a-copy.txt"))) {
String line;
while ((line = in.readLine()) != null) {
out.write(line);
out.newLine();
}
System.out.println("Copied");
} catch (FileNotFoundException e) {
System.out.println("Source file not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("I/O error: " + e.getMessage());
}
}
} Advanced — File Handling
File handling exceptions
- All of these extend
IOException, which is a checked exception, exceptUncheckedIOException.
| Exception | When it happens |
|---|---|
IOException | General input / output failure (parent of the others) |
FileNotFoundException | java.io stream cannot open a file (missing, a folder, or no permission) |
NoSuchFileException | NIO: the path does not exist |
FileAlreadyExistsException | NIO: createFile, copy, or move target exists |
AccessDeniedException | NIO: no permission, or the file is locked |
DirectoryNotEmptyException | Deleting a folder that still has entries |
EOFException | DataInputStream / ObjectInputStream read past the end |
UncheckedIOException | Unchecked wrapper thrown inside streams such as Files.lines |
Binary files: copying images and PDFs
- Never use
Reader/Writerfor binary data; character decoding corrupts the bytes. - Use byte streams with a buffer,
InputStream.transferTo(Java 9), or simplyFiles.copy.
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class BinaryCopy {
public static void main(String[] args) throws IOException {
// manual buffer
try (InputStream in = new BufferedInputStream(new FileInputStream("photo.jpg"));
OutputStream out = new BufferedOutputStream(new FileOutputStream("photo-copy.jpg"))) {
byte[] buf = new byte[8192];
int n;
while ((n = in.read(buf)) != -1) {
out.write(buf, 0, n);
}
}
// one line with NIO
Files.copy(Path.of("photo.jpg"), Path.of("photo-copy2.jpg"), StandardCopyOption.REPLACE_EXISTING);
}
} Reading and writing primitives with Data streams
DataOutputStreamwritesint,double,boolean, andUTFstrings in a fixed binary format.- Read them back in exactly the same order with
DataInputStream.
import java.io.*;
public class DataStreams {
public static void main(String[] args) throws IOException {
try (DataOutputStream out = new DataOutputStream(new FileOutputStream("scores.bin"))) {
out.writeUTF("Asha");
out.writeInt(92);
out.writeDouble(8.75);
}
try (DataInputStream in = new DataInputStream(new FileInputStream("scores.bin"))) {
System.out.println(in.readUTF() + " " + in.readInt() + " " + in.readDouble());
}
}
} Object serialization
- Serialization converts an object into bytes so it can be saved to a file and rebuilt later.
- The class must implement
Serializable. Mark fields you do not want saved (passwords, caches) astransient. - Declare
private static final long serialVersionUIDto control version compatibility. - Never deserialize data from untrusted sources; prefer JSON for data exchange in modern apps.
import java.io.*;
public class SerializeDemo {
static class Student implements Serializable {
private static final long serialVersionUID = 1L;
String name;
int marks;
transient String password; // not saved
Student(String name, int marks, String password) {
this.name = name; this.marks = marks; this.password = password;
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("student.ser"))) {
out.writeObject(new Student("Kiran", 88, "secret"));
}
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("student.ser"))) {
Student s = (Student) in.readObject();
System.out.println(s.name + " " + s.marks + " " + s.password); // Kiran 88 null
}
}
} Walking directories with Files.walk and Files.find
Files.listreturns direct children only;Files.walkgoes into every sub-folder.- Both return a
Streamthat holds open directory handles, so always use try-with-resources. - To delete a folder tree, delete children before parents: sort the walk results in reverse order.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.stream.Stream;
public class WalkDemo {
public static void main(String[] args) throws IOException {
Path root = Path.of("src");
try (Stream<Path> s = Files.walk(root)) {
s.filter(p -> p.toString().endsWith(".java"))
.forEach(System.out::println);
}
try (Stream<Path> s = Files.find(root, 10, (p, attr) -> attr.isRegularFile() && attr.size() > 10_000)) {
System.out.println("Large files: " + s.count());
}
// delete a whole folder tree (children first)
Path tmp = Path.of("tmp-out");
if (Files.exists(tmp)) {
try (Stream<Path> s = Files.walk(tmp)) {
s.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
}
}
}
} Large files, buffering, and atomic writes
readString,readAllLines, andreadAllBytesload the entire file into memory. Do not use them for multi-gigabyte files.- Stream large files with
BufferedReaderorFiles.lines, processing one line at a time. - Unbuffered
FileInputStream.read()makes one system call per byte. A buffer of 8 KB or more can be hundreds of times faster. - Safe save: write to a temporary file in the same folder, then
Files.move(tmp, target, ATOMIC_MOVE, REPLACE_EXISTING). Readers never see a half-written file.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class AtomicSave {
static void save(Path target, String content) throws IOException {
Path tmp = Files.createTempFile(target.toAbsolutePath().getParent(), "save-", ".tmp");
Files.writeString(tmp, content);
Files.move(tmp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
}
public static void main(String[] args) throws IOException {
save(Path.of("settings.json"), "{ \"theme\": \"dark\" }");
System.out.println(Files.readString(Path.of("settings.json")));
}
} Character encoding (charsets)
- Text files are bytes plus an encoding. Reading with the wrong encoding turns characters such as Hindi or Telugu letters into garbage.
- Before Java 18 the default charset was platform dependent (often Windows-1252 on Windows). Java 18+ defaults to UTF-8 (JEP 400).
Filesmethods always default to UTF-8. LegacyFileReader/FileWriteraccept aCharsetargument since Java 11.- Write portable code by passing
StandardCharsets.UTF_8explicitly.
Legacy finally-close vs try-with-resources
- Before Java 7 you had to close streams in
finally, with null checks and nested try blocks. - try-with-resources is shorter, closes in reverse order, and keeps the original exception (close failures are added as suppressed exceptions).
// Old style (before Java 7)
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("a.txt"));
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try { br.close(); } catch (IOException ignored) { }
}
}
// Modern style (Java 7+)
try (BufferedReader r = new BufferedReader(new FileReader("a.txt"))) {
System.out.println(r.readLine());
} catch (IOException e) {
e.printStackTrace();
} Tricky Interview Points
Q1) What is file handling in Java?
Answer Using java.io and java.nio.file APIs to create, read, write, append, copy, move, rename, and delete files and folders so data persists after the program ends.
Q2) File vs Path?
Answer File is the legacy pathname class whose methods return booleans. Path (NIO.2) with the Files utility class is the modern API: specific exceptions, copy and move, symbolic links, attributes, and Stream-based directory walking.
Q3) Does new File("a.txt") create a file?
Answer No. It only creates an object representing the path. Call createNewFile(), or open a FileWriter / FileOutputStream, to create the file on disk.
Q4) Byte stream vs character stream?
Answer Byte streams (InputStream / OutputStream) handle raw bytes for binary data. Character streams (Reader / Writer) handle text and apply a character encoding.
Q5) How do you append to a file instead of overwriting it?
Answer new FileWriter(file, true), or Files.writeString(path, text, StandardOpenOption.CREATE, StandardOpenOption.APPEND).
Q6) How do you read a large file line by line?
Answer Use BufferedReader.readLine() in a loop until it returns null, or Files.lines(path) inside try-with-resources. Both keep only one line in memory.
Q7) What does readLine() return at the end of the file?
Answer null. A single-character read() and byte read() return -1 at the end of the file.
Q8) What is try-with-resources?
Answer A try statement that declares AutoCloseable resources. Java closes them automatically in reverse order, even when an exception is thrown.
Q9) What happens if you forget to close a FileWriter?
Answer Buffered data may never be written to disk, the file handle leaks, and on Windows the file can stay locked.
Q10) Is IOException checked or unchecked?
Answer Checked. Callers must catch it or declare throws IOException. UncheckedIOException is its unchecked wrapper used inside streams.
Q11) FileNotFoundException vs NoSuchFileException?
Answer FileNotFoundException comes from java.io streams. NoSuchFileException comes from NIO Files methods. Both indicate the path cannot be opened.
Q12) How do you copy a file in Java?
Answer Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING) is simplest. Manually, read into a byte buffer from an InputStream and write to an OutputStream until read returns -1.
Q13) How do you delete a non-empty directory?
Answer Files.delete fails with DirectoryNotEmptyException. Walk the tree with Files.walk, sort in reverse order so children come first, and delete each path.
Q14) What is serialization? What does transient do?
Answer Serialization converts an object to bytes (ObjectOutputStream) so it can be stored and restored. transient fields are skipped and come back with default values.
Q15) Why specify UTF-8 explicitly?
Answer Before Java 18 the default charset depended on the operating system, so the same file could read differently on Windows and Linux. Passing StandardCharsets.UTF_8 makes code portable.
Q16) What does Files.writeString do if the file already exists?
Answer By default it truncates and overwrites the file. Pass StandardOpenOption.APPEND to add to the end, or CREATE_NEW to fail if it exists.
Q17) Why should Files.lines and Files.walk be closed?
Answer They are lazy Streams that keep file or directory handles open until the Stream is closed.
Simple Programs
Menu-driven file manager (create, write, read, append, delete)
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Scanner;
public class FileManager {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("File name: ");
Path p = Path.of(sc.nextLine().trim());
while (true) {
System.out.println("1.Create 2.Write 3.Read 4.Append 5.Delete 6.Info 0.Exit");
int ch = Integer.parseInt(sc.nextLine().trim());
try {
switch (ch) {
case 1 -> { Files.createFile(p); System.out.println("Created"); }
case 2 -> { System.out.print("Text: "); Files.writeString(p, sc.nextLine() + System.lineSeparator()); }
case 3 -> System.out.print(Files.readString(p));
case 4 -> { System.out.print("Text: ");
Files.writeString(p, sc.nextLine() + System.lineSeparator(),
StandardOpenOption.CREATE, StandardOpenOption.APPEND); }
case 5 -> System.out.println(Files.deleteIfExists(p) ? "Deleted" : "No such file");
case 6 -> System.out.println(p.toAbsolutePath() + " : " + Files.size(p) + " bytes");
case 0 -> { return; }
default -> System.out.println("Invalid choice");
}
} catch (IOException e) {
System.out.println("Error: " + e.getClass().getSimpleName() + " - " + e.getMessage());
}
}
}
} Count lines, words, and characters in a file
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class WordCount {
public static void main(String[] args) throws IOException {
int lines = 0, words = 0, chars = 0;
try (BufferedReader br = new BufferedReader(new FileReader("a.txt"))) {
String line;
while ((line = br.readLine()) != null) {
lines++;
chars += line.length();
String t = line.trim();
if (!t.isEmpty()) words += t.split("\\s+").length;
}
}
System.out.println("Lines=" + lines + " Words=" + words + " Chars=" + chars);
}
} Search a word in a file and print line numbers
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class SearchWord {
public static void main(String[] args) throws IOException {
String word = "java";
List<String> lines = Files.readAllLines(Path.of("notes.txt"));
int found = 0;
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).toLowerCase().contains(word)) {
System.out.println("Line " + (i + 1) + ": " + lines.get(i));
found++;
}
}
System.out.println(found == 0 ? "Not found" : found + " matching line(s)");
}
} Read a CSV file into objects and write a report
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class CsvReport {
record Student(String name, int marks) { }
public static void main(String[] args) throws IOException {
Path csv = Path.of("students.csv");
Files.writeString(csv, "name,marks\nAsha,91\nRavi,67\nMeena,78\n");
List<Student> list = new ArrayList<>();
List<String> rows = Files.readAllLines(csv);
for (String line : rows.subList(1, rows.size())) { // skip header
String[] parts = line.split(",");
list.add(new Student(parts[0].trim(), Integer.parseInt(parts[1].trim())));
}
try (PrintWriter pw = new PrintWriter("report.txt")) {
pw.printf("%-8s %5s %6s%n", "Name", "Marks", "Result");
for (Student s : list) {
pw.printf("%-8s %5d %6s%n", s.name(), s.marks(), s.marks() >= 70 ? "PASS" : "RETRY");
}
}
System.out.print(Files.readString(Path.of("report.txt")));
}
} Copy any file with a byte buffer and show progress
import java.io.*;
public class CopyWithProgress {
public static void main(String[] args) throws IOException {
File src = new File("video.mp4");
File dst = new File("video-copy.mp4");
long total = src.length(), done = 0;
try (InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst)) {
byte[] buf = new byte[64 * 1024];
int n;
while ((n = in.read(buf)) != -1) {
out.write(buf, 0, n);
done += n;
System.out.printf("Copied %d%%%n", total == 0 ? 100 : done * 100 / total);
}
}
}
} List all .java files in a project with their sizes
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class ListJavaFiles {
public static void main(String[] args) throws IOException {
Path root = Path.of(args.length > 0 ? args[0] : ".");
try (Stream<Path> s = Files.walk(root)) {
s.filter(Files::isRegularFile)
.filter(p -> p.getFileName().toString().endsWith(".java"))
.forEach(p -> {
try {
System.out.printf("%8d %s%n", Files.size(p), root.relativize(p));
} catch (IOException e) {
System.out.println("Cannot read " + p);
}
});
}
}
} Merge two files into one
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class MergeFiles {
public static void main(String[] args) throws IOException {
Path out = Path.of("merged.txt");
Files.deleteIfExists(out);
for (String name : new String[]{"part1.txt", "part2.txt"}) {
Path p = Path.of(name);
if (Files.exists(p)) {
Files.write(out, Files.readAllBytes(p), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} else {
System.out.println("Skipping missing " + name);
}
}
System.out.println("Merged size: " + Files.size(out) + " bytes");
}
} Problem Solving Tricks
- Prefer
Path.ofandFilesfor new code; convert withfile.toPath()/path.toFile()when an old API needsFile. - Remember end-of-file signals:
readLine()returnsnull;read()returns -1. - Text uses
Reader/Writer; images, PDFs, and ZIP files useInputStream/OutputStream. - Always open streams in try-with-resources. Several resources can be declared, separated by
;. - Append mode:
new FileWriter(name, true)orStandardOpenOption.APPEND(addCREATEfor the first run). - Use
Files.deleteIfExistswhen a missing file is not an error. - Build paths with
Path.of("dir", "file.txt")orresolve, not string concatenation with slashes. - Pass
StandardCharsets.UTF_8explicitly so files read the same on every operating system. - Never call
readAllLineson a huge log file; stream it withFiles.linesinstead. - Close
Files.lines,Files.list, andFiles.walkstreams; they hold open handles. - Never leave an empty catch block for
IOException; at least print a clear message.
Practice Programs List
- Create a file
students.txtand write five student names into it, one per line. - Read
students.txtback usingBufferedReader,Scanner, andFiles.readAllLines, and compare the code. - Append a timestamp line to
log.txtevery time the program runs. - Print a file name, absolute path, size, and last-modified date using
Filemethods. - Count lines, words, and characters in a text file.
- Copy a text file with
BufferedReader/BufferedWriterand a binary image with byte streams. - Search for a word in a file and print every line number where it appears.
- Rename
old.txttonew.txtwithFiles.move, then delete it withFiles.deleteIfExists. - Create the folder tree
data/2026/octoberin one call and place a file inside it. - List every
.javafile under a folder (including sub-folders) usingFiles.walk. - Read numbers from
numbers.txtwithScannerand print their sum and average. - Read
students.csvinto a list of records and write a formatted report withPrintWriter. - Save and load a
Studentobject with serialization; mark one fieldtransientand observe the result. - Handle a missing file with a friendly message instead of a stack trace.