00:00

Java File Handling Interview Questions and Answers

Last updated:

File handling questions appear in almost every Java interview, from fresher rounds to senior roles. Interviewers use them to check whether you understand streams, character encoding, resource management and the modern NIO.2 API. This page collects the most frequently asked questions with short, accurate answers that you can explain in your own words, followed by common coding questions with complete, tested solutions.

The questions start with the basics and become more advanced. Each answer links to a detailed tutorial in this series if you want to go deeper.

1. Basic Questions

Q1. What is file handling in Java?

File handling is how a Java program creates, reads, writes, copies, deletes and lists files and folders. Java provides two APIs for it: the classic java.io package (Java 1.0) and NIO.2 in java.nio.file (Java 7). See File Handling in Java.

Q2. Which packages are used for file handling?

java.io for File and the byte and character streams, java.nio.file for Path, Paths and Files, and java.nio.channels for channels such as FileChannel.

Q3. What is the File class, and does new File("a.txt") create a file?

java.io.File represents the path of a file or folder. Creating the object does not create anything on disk; you must call a method such as createNewFile() or mkdirs(). See File Class in Java.

Q4. What is a stream in Java I/O?

An ordered, one-way flow of data between a program and a source or destination. Input streams read data into the program; output streams write data out. It is unrelated to the Java 8 java.util.stream API. See Java I/O Streams.

Q5. What are the four abstract base classes of java.io streams?

InputStream and OutputStream for bytes, and Reader and Writer for characters.

Q6. What is the difference between an absolute and a relative path?

An absolute path is complete, such as /home/asha/report.txt or C:\data\report.txt. A relative path, such as data/report.txt, is resolved against the current working directory, which is stored in the user.dir system property. path.toAbsolutePath() and file.getAbsolutePath() convert a relative path.

Q7. How do you check whether a file exists?

Use Files.exists(path) or file.exists(). The documentation warns that the result is immediately outdated: another program may create or delete the file right after the check. So do not check and then act; call the operation directly and handle its exception.

Q8. How do you get the size of a file?

Files.size(path) returns the size in bytes and throws an exception if the file does not exist. file.length() also returns the size, but returns 0 for a missing file, so you cannot tell an empty file from a missing one.

Q9. How do you read a whole text file in one line?

Since Java 11, Files.readString(path) returns the content as a String, decoded as UTF-8. Files.readAllLines(path) returns a List<String>. Both load the whole file into memory. See How to Read a File.

Q10. How do you write text to a file in one line?

Files.writeString(path, text) (Java 11). With no options, it creates the file if needed and replaces existing content. See How to Write to a File.

Q11. How do you append to a file instead of overwriting it?

Pass StandardOpenOption.APPEND (together with CREATE if the file may not exist) to NIO.2 methods, or pass true as the append argument of FileWriter or FileOutputStream. See How to Append to a File.

Q12. How do you rename or move a file?

Files.move(source, target), adding StandardCopyOption.REPLACE_EXISTING to overwrite an existing target. The older File.renameTo() only returns false on failure, and its documentation says that much of its behavior is platform-dependent; for example, it may not move a file to another file system.

Q13. How do you write a platform-independent line break?

Use System.lineSeparator() (Java 7), BufferedWriter.newLine() or println(). A hard-coded \n is fine when a file format requires exactly that character.

Q14. What is the difference between FileNotFoundException and NoSuchFileException?

FileNotFoundException is thrown by java.io constructors such as FileInputStream when a file cannot be opened. NoSuchFileException is thrown by NIO.2 methods such as Files.delete() when the path does not exist. Both are subclasses of IOException.

Q15. Is IOException checked or unchecked?

Checked. Code that can throw it must catch it or declare it with throws. When a lambda cannot throw checked exceptions, it can be wrapped in UncheckedIOException (Java 8).

2. Byte and Character Stream Questions

Q16. What is the difference between byte streams and character streams?

Byte streams read and write raw 8-bit bytes without interpreting them and suit binary files. Character streams read and write 16-bit char values and convert to and from bytes with a charset, so they suit text. See Byte Stream vs Character Stream.

Q17. Why does read() return an int instead of a byte?

So it can return every byte value as 0 to 255 and still use -1 to signal the end of the stream. A byte could not tell 255 apart from -1. Reader.read() returns an int for the same reason: 0 to 65535 for a character, or -1.

Q18. What do InputStreamReader and OutputStreamWriter do?

They are bridges between the two families: InputStreamReader decodes bytes from an InputStream into characters, and OutputStreamWriter encodes characters into bytes for an OutputStream, both using a charset. See InputStreamReader.

Q19. Which design pattern do Java I/O streams use?

The Decorator pattern. A filter stream such as BufferedInputStream or DataInputStream wraps another stream and adds a feature, while still being an InputStream itself. That is why streams can be stacked: new DataInputStream(new BufferedInputStream(new FileInputStream(file))).

Q20. What happens if you read text with the wrong charset?

The bytes are decoded into the wrong characters (garbled text, called mojibake), or invalid sequences are replaced or reported as errors. Always read with the charset the file was written with.

Q21. What is the default charset in Java?

Since Java 18 (JEP 400), the default charset is UTF-8 on every platform. Before that it depended on the operating system, so passing a charset explicitly was essential for portable code.

Q22. What is the difference between FileReader and FileInputStream?

FileInputStream reads raw bytes; FileReader extends InputStreamReader and decodes those bytes into characters. Use FileReader (with a charset, Java 11+) for text and FileInputStream for binary data.

Q23. What is the difference between Scanner and BufferedReader?

BufferedReader reads lines quickly and throws IOException. Scanner splits input into tokens and parses them (nextInt(), nextDouble()) using regular expressions, which is convenient but slower for large files. Scanner also hides I/O errors: you must call ioException() to see them. Use BufferedReader for large text files and Scanner for small, structured input.

Q24. What is RandomAccessFile?

A class that can read and write at any position in a file, instead of only from start to end. seek(long) moves the file pointer and getFilePointer() returns it. The mode is "r" (read-only), "rw", "rws" or "rwd"; the last two also write changes to the storage device synchronously. It suits fixed-size records, such as updating record 500 of a data file.

Q25. What is serialization, and what does transient mean?

Serialization converts an object into bytes with ObjectOutputStream, and deserialization rebuilds it with ObjectInputStream. The class must implement the marker interface Serializable. Fields marked transient are skipped, which is useful for passwords or cached values. A serialVersionUID identifies the class version, so declare it explicitly. See Serialization in Java.

Q26. What are DataInputStream and DataOutputStream used for?

Reading and writing Java primitive values (int, long, double, boolean) and modified UTF-8 strings in a portable binary format, high byte first. Values must be read back in exactly the order they were written. See DataOutputStream.

Q27. What are ByteArrayInputStream and StringReader used for?

They let stream-based code read data that is already in memory: ByteArrayInputStream reads a byte[] and StringReader reads a String. They are popular in unit tests because no temporary files are needed. See ByteArrayInputStream.

3. Buffering and Resource Questions

Q28. Why use BufferedReader or BufferedInputStream?

They read data in large blocks into memory and answer small reads from that buffer, which sharply reduces slow system calls. BufferedReader also adds readLine() and lines().

Q29. What is the default buffer size of BufferedReader, and can you change it?

The documentation only says that the default is large enough for most purposes, so do not rely on an exact number. Pass a size to the constructor, for example new BufferedReader(reader, 64 * 1024), if measurements show it helps.

Q30. What is the difference between flush() and close()?

flush() pushes buffered data to the destination but keeps the stream open. close() normally flushes and then releases the resource; a closed stream cannot be used again. flush() passes data to the operating system but does not guarantee it is on the physical disk.

Q31. When you wrap streams, do you need to close each one?

No. Closing the outermost stream closes the stream it wraps; for example, FilterInputStream.close() simply calls in.close(). Closing only the inner stream is a mistake, because data in the outer buffer may not be written.

Q32. What is try-with-resources and why is it recommended for files?

A Java 7 form of try that automatically closes every resource declared in its header, in reverse order, even when an exception occurs. Any class that implements AutoCloseable can be used.

Try-with-resources
try (BufferedReader in = Files.newBufferedReader(path)) {
    System.out.println(in.readLine());
}   // in is closed here automatically

Q33. What is a suppressed exception?

If the try block throws an exception and close() then throws another, try-with-resources keeps the first one and attaches the second with addSuppressed(). You can read them with getSuppressed() (both Java 7). A classic try/finally would lose the original exception instead. The coding question below shows it.

Q34. What changed in try-with-resources in Java 9?

An existing variable can be used as a resource if it is final or effectively final, without declaring a new variable: try (reader) { ... }.

Q35. What happens if you forget to close a BufferedWriter?

Text still in its buffer may never reach the file, and the file handle stays open until the object is garbage-collected, if ever. Always close writers, ideally with try-with-resources.

Q36. What is the difference between PrintStream and PrintWriter?

PrintStream is a byte stream (for example System.out); PrintWriter is a character stream. Neither throws IOException; both report errors through checkError(). With auto-flush enabled, PrintWriter flushes only on println, printf and format. See PrintWriter.

4. NIO.2: Path and Files Questions

Q37. What is the difference between File and Path?

Path (Java 7) is the modern, immutable replacement for File. NIO.2 operations on Path throw descriptive exceptions, while many File methods only return false or null. Convert with file.toPath() and path.toFile(). See Java NIO vs IO.

Q38. What is the difference between java.io and NIO?

java.io is stream-oriented: data flows one byte or character at a time through blocking streams. NIO (Java 1.4) works with buffers and channels, and adds selectors for non-blocking network I/O. NIO.2 (Java 7) added Path, Files, file attributes and directory watching.

Q39. What is the difference between Path.of() and Paths.get()?

They produce the same result. Path.of() was added in Java 11, and the Paths documentation recommends it because Paths may be deprecated in a future release. See Path and Paths.

Q40. What do resolve(), relativize() and normalize() do?

resolve() joins paths: Path.of("logs").resolve("app.log") gives logs/app.log. relativize() does the opposite and builds the relative path from one path to another. normalize() removes redundant parts such as . and dir/... None of them touch the file system.

Q41. Which charset do the Files helper methods use?

Methods such as Files.readString(path), Files.readAllLines(path), Files.lines(path) and Files.newBufferedReader(path) always use UTF-8 when no charset is given, even on Java versions older than 18. Overloads accept another Charset.

Q42. How do you copy a file, and what if the target exists?

Files.copy(source, target). If the target exists, it throws FileAlreadyExistsException unless you pass StandardCopyOption.REPLACE_EXISTING. See How to Copy a File.

Q43. How do you delete a folder that is not empty?

Delete its contents first. Walk the tree with Files.walk(), sort the paths in reverse order so the deepest entries come first, and delete each one. A direct Files.delete() on a non-empty folder throws DirectoryNotEmptyException. See How to Delete a File.

Q44. What is the difference between Files.list() and Files.walk()?

Files.list() returns the entries of one folder; Files.walk() visits the folder and its whole sub-tree, depth-first, with an optional maximum depth. Both return a Stream<Path> that must be closed. See How to List Files.

Q45. When would you use Files.walkFileTree() instead of Files.walk()?

When you need callbacks at each stage of the walk. A FileVisitor (usually a SimpleFileVisitor) receives preVisitDirectory(), visitFile(), visitFileFailed() and postVisitDirectory(), and can skip sub-trees or stop early. It suits tasks such as copying or deleting a tree, or carrying on past unreadable files.

Q46. How do you find files that match a pattern such as *.java?

Use a glob: Files.newDirectoryStream(dir, "*.java") for one folder, or FileSystems.getDefault().getPathMatcher("glob:**/*.java") with Files.walk() or Files.find() for a whole tree. The prefix regex: uses a regular expression instead.

Q47. How do you read file attributes such as size and modification time?

For one value, use Files.size(), Files.getLastModifiedTime() or Files.isHidden(). To read several at once, use Files.readAttributes(path, BasicFileAttributes.class), which returns size, creation time, last modified time and the file type in one call. Platform-specific views, such as PosixFileAttributes, add permissions and owners.

Q48. How do Files methods handle symbolic links?

Most methods follow symbolic links by default; pass LinkOption.NOFOLLOW_LINKS to work on the link itself. Files.walk() does not follow links unless you pass FileVisitOption.FOLLOW_LINKS. Files.isSymbolicLink() tells you whether a path is a link.

Q49. How do you watch a folder for new or changed files?

Use a WatchService (Java 7). Register the folder with path.register(watcher, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE), then call take() or poll() to receive events. It watches one folder, not its sub-folders, and events can be lost (reported as OVERFLOW), so be ready to rescan.

5. Advanced Questions

Q50. Why must the streams from Files.lines(), Files.list() and Files.walk() be closed?

They hold an open file or open folders until closed. Their documentation says to use them within a try-with-resources statement, otherwise file handles leak.

Q51. How do you read a very large file without running out of memory?

Process it piece by piece: BufferedReader.readLine() or Files.lines() for text, and a buffered byte stream or readNBytes() chunks for binary data. Avoid readAllBytes(), readString() and readAllLines() for such files.

Q52. How do you create a file only if it does not already exist, safely?

Use Files.createFile() or write with StandardOpenOption.CREATE_NEW. Both check for existence and create the file in one step and throw FileAlreadyExistsException otherwise. Checking Files.exists() first is unsafe, because another program can create the file in between.

Q53. How do you save a file so that readers never see a half-written version?

Write the new content to a temporary file in the same folder, then replace the target with Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE). If the file system cannot move atomically (for example, across file systems), AtomicMoveNotSupportedException is thrown. The coding question below shows the full pattern.

Q54. What is FileChannel, and what is a memory-mapped file?

FileChannel reads and writes files through ByteBuffers, at any position. It can copy data directly between channels with transferTo()/transferFrom(), lock regions of a file, and map a file into memory with map(). A memory-mapped file (MappedByteBuffer) lets you access file content like an array, which is fast for large files read at random positions.

Q55. How do you lock a file in Java?

Use FileChannel.lock() or tryLock(), which return a FileLock. File locks are held on behalf of the whole JVM, so they coordinate separate programs, not threads in the same program. On some systems locks are only advisory: other programs must also use locks for them to have any effect.

Q56. Is it safe for several threads to write to the same file?

Not unless you coordinate them. Writes from different threads can interleave and corrupt lines. Common solutions are a single writer thread fed by a queue, synchronizing on the writer, or using a logging framework that handles this for you.

Q57. How do you read a file that is packaged inside a JAR (from the classpath)?

Use getClass().getResourceAsStream("/config/app.properties") or the class loader version, and wrap the result in a reader. It returns null if the resource is missing, so check for that. Files and File cannot open files inside a JAR by their path.

Q58. What is the difference between Files.readString() and new String(Files.readAllBytes(path))?

Both read the whole file. new String(bytes, charset) always replaces invalid byte sequences with a replacement character, silently. Files.readString() throws an exception for malformed input instead, so encoding problems are detected.

Q59. How do you create temporary files, and where are they stored?

Files.createTempFile(prefix, suffix) and Files.createTempDirectory(prefix) create them with unique names in the folder given by the java.io.tmpdir system property. They are not deleted automatically, so delete them yourself, for example in a finally block.

Q60. Why is deserializing untrusted data dangerous?

Deserialization can create objects of many classes and run their code, so crafted bytes can trigger unexpected behavior. Never deserialize data from untrusted sources; if you must, restrict the allowed classes with an ObjectInputFilter (Java 9), or use a data format such as JSON instead.

6. Java 9 to Java 25 Questions

Q61. Which file I/O methods were added after Java 8?

Java 9: InputStream.readAllBytes() and transferTo(). Java 10: Reader.transferTo(). Java 11: Files.readString(), Files.writeString(), Path.of() and the null streams, readers and writers. Java 12: Files.mismatch(). Java 22: Path.resolve(first, more...). Java 24: Reader.of(CharSequence).

Q62. How did JEP 400 (Java 18) affect existing programs?

Code that read or wrote text without a charset, such as new FileReader(file), now uses UTF-8 everywhere. Programs that relied on another platform charset, common on older Windows systems, may read old files incorrectly. The native.encoding system property reports the operating system's charset, and -Dfile.encoding=COMPAT restores the old behavior. The best fix is to pass the charset explicitly.

Q63. How do you compare the content of two files?

Since Java 12, Files.mismatch(a, b) returns -1 if the contents are identical, or the position of the first different byte. Do not confuse it with Files.isSameFile(), which checks whether two paths point to the same file.

Q64. How do you read input from the console in modern Java?

Java 25 adds IO.readln("Prompt: ") in java.lang.IO. Older options are Scanner(System.in), BufferedReader(new InputStreamReader(System.in)) and System.console(), which also offers readPassword().

Q65. Did Java 25 change file handling?

Java 25 adds no new file APIs; everything in this series is standard and current. Its new java.lang.IO class (IO.println(), IO.readln()) simplifies console input and output for beginners, not file access.

7. Coding Questions with Solutions

Interviewers often ask you to write a short program. Each solution below is a complete Java 25 program that creates its own temporary files, so you can run it as it is.

Q66. Write a program to count the lines, words and characters in a file.

Read the file line by line so that even a huge file uses little memory.

WordCount.java
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class WordCount {
    public static void main(String[] args) throws IOException {
        Path notes = Files.createTempFile("meeting-notes", ".txt");
        Files.writeString(notes, """
                Sprint review moved to Friday
                Demo the new search page
                Fix the login timeout before release
                """);

        long lines = 0;
        long words = 0;
        long chars = 0;
        try (BufferedReader reader = Files.newBufferedReader(notes)) {
            String line;
            while ((line = reader.readLine()) != null) {   // one line in memory at a time
                lines++;
                chars += line.length();
                String text = line.strip();
                if (!text.isEmpty()) {
                    words += text.split("\\s+").length;
                }
            }
        }
        System.out.println("Lines: " + lines);
        System.out.println("Words: " + words);
        System.out.println("Characters (without line breaks): " + chars);
        Files.delete(notes);
    }
}
Output
Lines: 3
Words: 16
Characters (without line breaks): 89
  1. Files.newBufferedReader() reads UTF-8 text and readLine() returns one line at a time.
  2. strip() removes leading and trailing spaces, and split("\\s+") splits on any run of whitespace.
  3. Empty lines are skipped, because splitting an empty string would count one word.

Q67. Find the longest line in a file.

A stream of lines with max() solves this in one statement.

LongestLine.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;

public class LongestLine {
    public static void main(String[] args) throws IOException {
        Path log = Files.createTempFile("server", ".log");
        Files.write(log, List.of(
                "08:00 server started",
                "08:05 cache warmed with 1200 product entries",
                "08:09 health check ok"));

        try (Stream<String> lines = Files.lines(log)) {
            lines.max(Comparator.comparingInt(String::length))
                 .ifPresent(line -> System.out.println("Longest line (" + line.length() + " chars): " + line));
        }
        Files.delete(log);
    }
}
Output
Longest line (44 chars): 08:05 cache warmed with 1200 product entries
  1. Files.lines() reads lines lazily and is closed by try-with-resources.
  2. Comparator.comparingInt(String::length) compares lines by length, and max() returns an Optional, empty for an empty file.

Q68. Find the three most frequent words in a file.

This is a common follow-up that combines file reading with collections.

TopWords.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Locale;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TopWords {
    public static void main(String[] args) throws IOException {
        Path feedback = Files.createTempFile("feedback", ".txt");
        Files.writeString(feedback, """
                Fast delivery and good packaging.
                Delivery was fast, support was helpful.
                Good price, fast delivery.
                """);

        Map<String, Long> counts;
        try (Stream<String> lines = Files.lines(feedback)) {
            counts = lines
                    .flatMap(line -> Arrays.stream(line.toLowerCase(Locale.ROOT).split("[^a-z]+")))
                    .filter(word -> !word.isEmpty())
                    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        }

        counts.entrySet().stream()
              .sorted(Map.Entry.<String, Long>comparingByValue().reversed()
                      .thenComparing(Map.Entry.comparingByKey()))
              .limit(3)
              .forEach(e -> System.out.println(e.getKey() + " = " + e.getValue()));
        Files.delete(feedback);
    }
}
Output
delivery = 3
fast = 3
good = 2
  1. Each line is lower-cased with Locale.ROOT and split on every character that is not a letter.
  2. groupingBy(..., counting()) builds a word-to-count map.
  3. The entries are sorted by count (descending), then alphabetically, so ties always appear in the same order.

Q69. Merge two files into one.

Branch offices send order files that must be combined into one file.

MergeFiles.java
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class MergeFiles {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("orders");
        Path north = Files.writeString(dir.resolve("north.csv"), "N-101,Laptop\nN-102,Monitor\n");
        Path south = Files.writeString(dir.resolve("south.csv"), "S-201,Keyboard\n");
        Path merged = dir.resolve("all-orders.csv");

        try (OutputStream out = Files.newOutputStream(merged)) {
            for (Path part : List.of(north, south)) {
                Files.copy(part, out);   // streams each file's bytes into the merged file
            }
        }

        System.out.print(Files.readString(merged));
        System.out.println("Merged size: " + Files.size(merged) + " bytes");

        for (Path p : List.of(north, south, merged, dir)) {
            Files.delete(p);
        }
    }
}
Output
N-101,Laptop
N-102,Monitor
S-201,Keyboard
Merged size: 42 bytes
  1. Files.newOutputStream() creates the merged file.
  2. Files.copy(Path, OutputStream) streams each file into it without loading it into memory.
  3. The merged file contains 13 + 14 + 15 = 42 bytes.

Q70. Count the files in a folder tree by extension.

A build tool reports how many files of each type a project contains.

CountByExtension.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CountByExtension {
    static String extension(Path file) {
        String name = file.getFileName().toString();
        int dot = name.lastIndexOf('.');
        return dot < 0 ? "(none)" : name.substring(dot + 1);
    }

    public static void main(String[] args) throws IOException {
        Path project = Files.createTempDirectory("project");
        for (String name : List.of("src/App.java", "src/util/Dates.java", "docs/guide.md",
                                   "docs/api.md", "README.md", "build.gradle", "LICENSE")) {
            Path file = project.resolve(name);
            Files.createDirectories(file.getParent());
            Files.createFile(file);
        }

        Map<String, Long> byExtension;
        try (Stream<Path> paths = Files.walk(project)) {
            byExtension = paths.filter(Files::isRegularFile)
                               .collect(Collectors.groupingBy(CountByExtension::extension, TreeMap::new, Collectors.counting()));
        }
        byExtension.forEach((ext, count) -> System.out.println(ext + ": " + count));

        try (Stream<Path> paths = Files.walk(project)) {           // clean up, deepest paths first
            for (Path p : paths.sorted(Comparator.reverseOrder()).toList()) {
                Files.delete(p);
            }
        }
    }
}
Output
(none): 1
gradle: 1
java: 2
md: 3
  1. Files.walk() visits every path, and Files::isRegularFile keeps only files.
  2. groupingBy with a TreeMap sorts the extensions alphabetically.
  3. The cleanup walk deletes the deepest paths first, so every folder is empty when it is deleted.

Q71. Check whether two files have the same content.

A deployment script checks whether a configuration file has changed.

CompareFiles.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class CompareFiles {
    public static void main(String[] args) throws IOException {
        Path a = Files.createTempFile("config-a", ".properties");
        Path b = Files.createTempFile("config-b", ".properties");
        Path c = Files.createTempFile("config-c", ".properties");
        Files.writeString(a, "timeout=30\nretries=3\n");
        Files.writeString(b, "timeout=30\nretries=3\n");
        Files.writeString(c, "timeout=30\nretries=5\n");

        System.out.println("a vs b: " + Files.mismatch(a, b));      // -1 means identical content
        System.out.println("a vs c: " + Files.mismatch(a, c));      // index of the first different byte
        System.out.println("a and b are the same file? " + Files.isSameFile(a, b));

        for (Path p : List.of(a, b, c)) {
            Files.delete(p);
        }
    }
}
Output
a vs b: -1
a vs c: 19
a and b are the same file? false
  1. Files.mismatch() returns -1 for a and b, which have the same bytes.
  2. For a and c, it returns 19: the 11 bytes of timeout=30\n plus the 8 bytes of retries=, so byte 19 is the first difference.
  3. isSameFile() returns false because they are different files, even though the content is equal.

Q72. Save a settings file safely so a crash never leaves it half-written.

This is the atomic save pattern from the advanced questions.

AtomicSave.java
import java.io.IOException;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.stream.Stream;

public class AtomicSave {
    static void save(Path target, String content) throws IOException {
        // Write to a temporary file in the same folder, then move it over the target in one step
        Path temp = Files.createTempFile(target.getParent(), "save-", ".tmp");
        try {
            Files.writeString(temp, content);
            try {
                Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE);
            } catch (AtomicMoveNotSupportedException e) {
                Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);
            }
        } finally {
            Files.deleteIfExists(temp);   // only does something if the move failed
        }
    }

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("app");
        Path settings = dir.resolve("settings.json");

        save(settings, "{\"theme\":\"light\"}");
        save(settings, "{\"theme\":\"dark\"}");

        System.out.println("Content: " + Files.readString(settings));
        try (Stream<Path> files = Files.list(dir)) {
            System.out.println("Files in folder: " + files.count());
        }
        Files.delete(settings);
        Files.delete(dir);
    }
}
Output
Content: {"theme":"dark"}
Files in folder: 1
  1. The content is first written to a temporary file in the same folder.
  2. ATOMIC_MOVE replaces the target in a single file system operation, so readers see either the old or the new file. Whether an existing target is replaced is platform-specific; the common platforms replace it.
  3. If an atomic move is not supported, the code falls back to a normal move with REPLACE_EXISTING.
  4. Only one file remains in the folder after two saves.

Q73. Show what happens when both the try block and close() throw an exception.

This question tests whether you understand try-with-resources in depth.

SuppressedDemo.java
import java.io.IOException;

public class SuppressedDemo {
    static class Connection implements AutoCloseable {
        private final String name;

        Connection(String name) {
            this.name = name;
            System.out.println("open " + name);
        }

        String name() {
            return name;
        }

        @Override
        public void close() throws IOException {
            System.out.println("close " + name);
            throw new IOException("close failed: " + name);
        }
    }

    public static void main(String[] args) {
        try (Connection first = new Connection("first");
             Connection second = new Connection("second")) {
            System.out.println("using " + first.name() + " and " + second.name());
            throw new IllegalStateException("body failed");
        } catch (Exception e) {
            System.out.println("Caught: " + e.getMessage());
            for (Throwable s : e.getSuppressed()) {
                System.out.println("Suppressed: " + s.getMessage());
            }
        }
    }
}
Output
open first
open second
using first and second
close second
close first
Caught: body failed
Suppressed: close failed: second
Suppressed: close failed: first
  1. The resources are opened in order and closed in reverse order: second, then first.
  2. The exception from the body is the one that is caught.
  3. Both close() exceptions are attached to it as suppressed exceptions instead of being lost.

8. Tips for Answering File Handling Questions

  • Always mention closing resources with try-with-resources.
  • Distinguish bytes from characters and name the charset (UTF-8).
  • Prefer NIO.2 (Path, Files) for new code, and explain why: clearer exceptions and shorter code.
  • Mention memory use: whole-file methods versus streaming for large files.
  • Point out race conditions: act directly and handle exceptions instead of checking first.
  • Back answers with a small code example when you can.

9. Summary

  • Java file handling uses java.io streams and the NIO.2 Path and Files API.
  • Byte streams handle binary data; character streams handle text with a charset.
  • Buffer streams, close them with try-with-resources and specify UTF-8.
  • Know the one-line Files helpers, their exceptions and safe patterns such as atomic saves.
  • Be ready to explain the Java 9–25 additions such as readString(), mismatch() and Reader.of().
  • Practise short coding tasks: counting, searching, merging and comparing files.

Related Tutorials

10. Official Java Documentation References