Skip to main content

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.

L1

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.io package (Java 1.0+) and the modern java.nio.file package (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).
OperationMeaningClassic java.ioModern java.nio.file
CreateMake a new empty file or folderfile.createNewFile(), mkdir()Files.createFile(p), createDirectories(p)
WriteReplace the contentFileWriter, BufferedWriterFiles.writeString(p, text)
ReadGet the contentFileReader, BufferedReader, ScannerFiles.readString(p), readAllLines(p)
AppendAdd to the endnew FileWriter(f, true)Files.writeString(p, t, APPEND)
CopyDuplicate a fileStreams in a loopFiles.copy(src, dst)
Move / renameChange location or namefile.renameTo(dest)Files.move(src, dst)
DeleteRemove a file or empty folderfile.delete()Files.delete(p), deleteIfExists(p)
InformationSize, dates, permissionslength(), lastModified()Files.size(p), getLastModifiedTime(p)

Differences between java.io.File and java.nio.file (Path / Files)

  • File and Path only describe a location. They do not hold content. Reading and writing is done by streams or the Files utility class.
  • Prefer Path + Files for new code. Use file.toPath() and path.toFile() to convert when an old API needs File.
Pointjava.io.Filejava.nio.file.Path + Files
IntroducedJava 1.0Java 7 (NIO.2)
Create a pathnew File("a.txt")Path.of("a.txt") (Java 11) or Paths.get("a.txt")
Error reportingReturns false with no reasonThrows a specific exception (NoSuchFileException, ...)
Read whole fileNeeds a stream and a loopFiles.readString, readAllLines, readAllBytes
Copy / moveNo built-in copy; renameTo unreliableFiles.copy, Files.move with options
Symbolic links and attributesVery limitedFull support (readAttributes, permissions)
Directory walkinglistFiles() and manual recursionFiles.list, walk, find (Streams)
Recommended for new codeNo (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.
ClassTypePurposeKey methods
FileInputStreamByte inputRead bytes from a fileread(), read(byte[]), readAllBytes()
FileOutputStreamByte outputWrite bytes to a filewrite(int), write(byte[])
BufferedInputStream / BufferedOutputStreamByte, bufferedFaster binary I/OSame as above plus flush()
DataInputStream / DataOutputStreamByteRead / write primitivesreadInt(), writeDouble(), readUTF()
ObjectInputStream / ObjectOutputStreamByteSerialize whole objectsreadObject(), writeObject()
FileReaderCharacter inputRead text from a fileread(), read(char[])
FileWriterCharacter outputWrite text to a filewrite(String), append()
BufferedReaderCharacter, bufferedRead text line by linereadLine(), lines()
BufferedWriterCharacter, bufferedWrite text efficientlywrite(), newLine(), flush()
PrintWriterCharacter outputFormatted text outputprintln(), printf()
ScannerText parserRead tokens, numbers, linesnextLine(), nextInt(), hasNext()
RandomAccessFileBoth directionsJump to any positionseek(), 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.
MethodReturn typeDescription
createNewFile()booleanCreates an empty file; false if it already exists. Throws IOException
exists()booleanDoes the file or folder exist?
isFile() / isDirectory()booleanIs it a regular file / a folder?
getName()StringFile name only, such as notes.txt
getPath()StringPath as given to the constructor
getAbsolutePath()StringFull path from the drive or root
getParent()StringParent folder path (or null)
length()longSize in bytes (0 if missing)
lastModified()longLast modified time in milliseconds since 1970
canRead() / canWrite() / canExecute()booleanPermission checks
setReadOnly() / setWritable(b)booleanChange permissions
delete()booleanDeletes a file or an empty folder
deleteOnExit()voidDeletes when the JVM exits (temporary files)
mkdir()booleanCreates one folder (parent must exist)
mkdirs()booleanCreates the folder and any missing parents
renameTo(File dest)booleanRenames or moves; platform dependent
list()String[]Names of entries in a folder
listFiles()File[]Entries as File objects (null if not a folder)
toPath()PathConvert to the NIO Path type

java.nio.file.Files class methods

  • Files contains only static methods. Every method that touches the disk throws IOException.
CategoryMethodDescription
CheckFiles.exists(p) / notExists(p)Does the path exist?
CheckFiles.isRegularFile(p) / isDirectory(p)File or folder?
CheckFiles.isReadable(p) / isWritable(p) / isHidden(p)Permission and visibility checks
CreateFiles.createFile(p)New empty file; throws FileAlreadyExistsException if present
CreateFiles.createDirectory(p) / createDirectories(p)One folder / folder with all parents
CreateFiles.createTempFile(prefix, suffix)Unique temporary file
ReadFiles.readString(p)Whole text file into one String (Java 11)
ReadFiles.readAllLines(p)All lines into a List<String>
ReadFiles.readAllBytes(p)Whole file into a byte[]
ReadFiles.lines(p)Lazy Stream<String> of lines; close it
ReadFiles.newBufferedReader(p)Opens a BufferedReader (UTF-8 by default)
WriteFiles.writeString(p, text, options...)Write a String (Java 11)
WriteFiles.write(p, lines) / write(p, bytes)Write a list of lines or a byte array
WriteFiles.newBufferedWriter(p, options...)Opens a BufferedWriter
Copy / moveFiles.copy(src, dst, options...)Copy a file; add REPLACE_EXISTING to overwrite
Copy / moveFiles.move(src, dst, options...)Move or rename; supports ATOMIC_MOVE
DeleteFiles.delete(p)Delete; throws NoSuchFileException if missing
DeleteFiles.deleteIfExists(p)Delete; returns false if missing
InfoFiles.size(p)Size in bytes
InfoFiles.getLastModifiedTime(p)Last modified time as FileTime
InfoFiles.probeContentType(p)Guess MIME type, such as text/plain
DirectoryFiles.list(dir)Stream of direct children
DirectoryFiles.walk(dir)Stream of every file and folder below dir
DirectoryFiles.find(dir, depth, matcher)Search by name, size, or date
CompareFiles.mismatch(p1, p2)Position of the first different byte, or -1 (Java 12)

Path interface methods

MethodExampleResult
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

ClassMethodDescription
FileWriternew FileWriter(name) / new FileWriter(name, true)Overwrite / append mode
FileWriter, BufferedWriterwrite(String)Write text (no newline added)
BufferedWriternewLine()Write the platform line separator
Any writer / output streamflush()Push buffered data to disk now
Any streamclose()Flush and release the file handle (use try-with-resources)
PrintWriterprintln(), printf(), format()Formatted text output
FileReaderread()One character as int; -1 at end of file
BufferedReaderreadLine()One line without the newline; null at end of file
BufferedReaderlines()Stream of remaining lines
ScannerhasNextLine(), nextLine()Line-by-line reading
ScannerhasNextInt(), nextInt(), next()Token and number reading
FileInputStreamread(), read(byte[] buf)Byte / chunk reading; -1 at end of file
FileInputStreamreadAllBytes(), transferTo(out)Read everything / copy to another stream (Java 9)
FileOutputStreamwrite(byte[] buf, off, len)Write part of a byte array

StandardOpenOption values

  • Pass these to Files.writeString, Files.write, or Files.newBufferedWriter to control how the file is opened.
OptionEffect
CREATECreate the file if it does not exist
CREATE_NEWCreate the file; fail if it already exists
APPENDWrite at the end of the file
TRUNCATE_EXISTINGEmpty the file before writing (default with CREATE and WRITE)
WRITEOpen for writing
READOpen for reading
DELETE_ON_CLOSEDelete the file when it is closed
SYNC / DSYNCWrite every change straight to the storage device

Create a file

  • File.createNewFile() returns false if the file is already there.
  • Files.createFile() throws FileAlreadyExistsException instead, so you know exactly what happened.
  • Create parent folders first with mkdirs() or Files.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 BufferedWriter or PrintWriter for many small writes; use Files.writeString for 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.readString or Files.readAllLines.
  • Large files: BufferedReader.readLine() in a loop or Files.lines so only one line is in memory at a time.
  • Scanner is 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 true as the second argument of FileWriter, or use StandardOpenOption.APPEND with Files.
  • Add CREATE so 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 AutoCloseable resource (Reader, Writer, InputStream, Scanner on a file, Stream from Files.lines) inside try ( ... ).
  • 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. Declare throws IOException in 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());
        }
    }
}
L2

Advanced — File Handling

File handling exceptions

  • All of these extend IOException, which is a checked exception, except UncheckedIOException.
ExceptionWhen it happens
IOExceptionGeneral input / output failure (parent of the others)
FileNotFoundExceptionjava.io stream cannot open a file (missing, a folder, or no permission)
NoSuchFileExceptionNIO: the path does not exist
FileAlreadyExistsExceptionNIO: createFile, copy, or move target exists
AccessDeniedExceptionNIO: no permission, or the file is locked
DirectoryNotEmptyExceptionDeleting a folder that still has entries
EOFExceptionDataInputStream / ObjectInputStream read past the end
UncheckedIOExceptionUnchecked wrapper thrown inside streams such as Files.lines

Binary files: copying images and PDFs

  • Never use Reader / Writer for binary data; character decoding corrupts the bytes.
  • Use byte streams with a buffer, InputStream.transferTo (Java 9), or simply Files.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

  • DataOutputStream writes int, double, boolean, and UTF strings 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) as transient.
  • Declare private static final long serialVersionUID to 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.list returns direct children only; Files.walk goes into every sub-folder.
  • Both return a Stream that 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, and readAllBytes load the entire file into memory. Do not use them for multi-gigabyte files.
  • Stream large files with BufferedReader or Files.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).
  • Files methods always default to UTF-8. Legacy FileReader / FileWriter accept a Charset argument since Java 11.
  • Write portable code by passing StandardCharsets.UTF_8 explicitly.

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();
}
L3

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.

L4

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");
    }
}
L5

Problem Solving Tricks

  • Prefer Path.of and Files for new code; convert with file.toPath() / path.toFile() when an old API needs File.
  • Remember end-of-file signals: readLine() returns null; read() returns -1.
  • Text uses Reader / Writer; images, PDFs, and ZIP files use InputStream / OutputStream.
  • Always open streams in try-with-resources. Several resources can be declared, separated by ;.
  • Append mode: new FileWriter(name, true) or StandardOpenOption.APPEND (add CREATE for the first run).
  • Use Files.deleteIfExists when a missing file is not an error.
  • Build paths with Path.of("dir", "file.txt") or resolve, not string concatenation with slashes.
  • Pass StandardCharsets.UTF_8 explicitly so files read the same on every operating system.
  • Never call readAllLines on a huge log file; stream it with Files.lines instead.
  • Close Files.lines, Files.list, and Files.walk streams; they hold open handles.
  • Never leave an empty catch block for IOException; at least print a clear message.
L6

Practice Programs List

  1. Create a file students.txt and write five student names into it, one per line.
  2. Read students.txt back using BufferedReader, Scanner, and Files.readAllLines, and compare the code.
  3. Append a timestamp line to log.txt every time the program runs.
  4. Print a file name, absolute path, size, and last-modified date using File methods.
  5. Count lines, words, and characters in a text file.
  6. Copy a text file with BufferedReader / BufferedWriter and a binary image with byte streams.
  7. Search for a word in a file and print every line number where it appears.
  8. Rename old.txt to new.txt with Files.move, then delete it with Files.deleteIfExists.
  9. Create the folder tree data/2026/october in one call and place a file inside it.
  10. List every .java file under a folder (including sub-folders) using Files.walk.
  11. Read numbers from numbers.txt with Scanner and print their sum and average.
  12. Read students.csv into a list of records and write a formatted report with PrintWriter.
  13. Save and load a Student object with serialization; mark one field transient and observe the result.
  14. Handle a missing file with a friendly message instead of a stack trace.