1Z0-819 I/O Operations 2 — Questions and Answers
Question 1: Which method in the `Files` class copies a file and replaces the destination if it already exists?
- Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING) (Correct answer)
- Files.copy(src, dst, StandardCopyOption.ATOMIC_MOVE)
- Files.move(src, dst, StandardCopyOption.REPLACE_EXISTING)
- Files.transfer(src, dst)
Correct answer: Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING)
`Files.copy` with `StandardCopyOption.REPLACE_EXISTING` overwrites the destination file if it exists.
Question 2: What does `Files.walk(path)` return?
- A `Stream<Path>` of all files in the directory tree (Correct answer)
- A `List<File>` of immediate children
- An `Iterator<Path>` of the directory
- A `DirectoryStream<Path>` of one level
Correct answer: A `Stream<Path>` of all files in the directory tree
`Files.walk` returns a lazy `Stream<Path>` that traverses the directory tree depth-first.
Question 3: Which `OpenOption` must be specified to append to an existing file using `Files.newOutputStream`?
- StandardOpenOption.APPEND (Correct answer)
- StandardOpenOption.WRITE
- StandardOpenOption.SYNC
- StandardOpenOption.TRUNCATE_EXISTING
Correct answer: StandardOpenOption.APPEND
`StandardOpenOption.APPEND` positions the stream at the end of the file before each write.
Question 4: What exception is thrown when you call `Files.readAllBytes` on a path that does not exist?
- NoSuchFileException (Correct answer)
- FileNotFoundException
- IOException
- IllegalArgumentException
Correct answer: NoSuchFileException
`Files.readAllBytes` throws `NoSuchFileException` (a subclass of `IOException`) when the file is absent.
Question 5: What is the result of `Path.relativize(other)` when `other` is not relative to the base path?
- It may include `..` segments to navigate up the tree (Correct answer)
- It throws IllegalArgumentException
- It returns the absolute path of `other`
- It returns an empty path
Correct answer: It may include `..` segments to navigate up the tree
`relativize` uses `..` components to express a path from base to target even when traversal above base is needed.
Question 6: Which class provides buffered character-based reading with a `readLine()` method?
- BufferedReader (Correct answer)
- FileReader
- InputStreamReader
- Scanner
Correct answer: BufferedReader
`BufferedReader` wraps a `Reader` and offers the `readLine()` convenience method.
Question 7: When using `try-with-resources` with multiple `AutoCloseable` resources, in what order are they closed?
- Reverse order of declaration (Correct answer)
- Order of declaration
- Alphabetical order by variable name
- Simultaneously in parallel
Correct answer: Reverse order of declaration
Resources are closed in the reverse order they are declared, ensuring proper cleanup of dependent resources.
Which method in the `Files` class copies a file and replaces the destination if it already exists?