OCP OCP Java IO and NIO 2 — Questions and Answers
Question 1: Which interface in Java NIO.2 (introduced in Java 7) represents a path to a file or directory on the file system?
- java.io.File
- java.nio.file.Path (Correct answer)
- java.nio.file.FilePath
- java.nio.file.FileReference
Correct answer: java.nio.file.Path
java.nio.file.Path is the NIO.2 interface introduced in Java 7 that represents a file system path and largely supersedes java.io.File.
Question 2: Which two factory methods can be used to create a Path object in Java NIO.2?
- Path.create() and Path.make()
- Paths.get() and Path.of() (Correct answer)
- Files.getPath() and Paths.create()
- Path.from() and Paths.toPath()
Correct answer: Paths.get() and Path.of()
Paths.get() (available since Java 7) and the static Path.of() method (added in Java 11) are both valid ways to create Path instances.
Question 3: What does the Files.walk() method return when called with a starting directory Path?
- An Iterator<Path> of all files in the directory
- A lazy Stream<Path> traversing the directory tree depth-first (Correct answer)
- A List<File> of every file found
- A DirectoryStream<Path> limited to direct children
Correct answer: A lazy Stream<Path> traversing the directory tree depth-first
Files.walk() returns a lazily populated Stream<Path> that traverses the file tree depth-first from the specified starting directory.
Question 4: Which StandardWatchEventKinds constant signals that a new file or directory was created in a directory watched by WatchService?
- ENTRY_CREATED (Correct answer)
- FILE_CREATED
- NEW_ENTRY
- WATCH_CREATE
Correct answer: ENTRY_CREATED
StandardWatchEventKinds.ENTRY_CREATED is the WatchEvent.Kind raised when a new file or directory entry appears in a watched directory.
Question 5: What is the difference between Path.resolve() and Path.relativize() in Java NIO.2?
- resolve() combines two paths into one; relativize() computes the relative path between two paths (Correct answer)
- resolve() reads the file content; relativize() writes relative content
- resolve() works only with absolute paths; relativize() works only with relative paths
- They are interchangeable aliases for the same operation
Correct answer: resolve() combines two paths into one; relativize() computes the relative path between two paths
Path.resolve() appends one path to another to form a combined path, while Path.relativize() computes the relative path needed to navigate from one path to another.
Question 6: Which Files utility method in NIO.2 copies a file from a source Path to a target Path?
- Files.duplicate()
- Files.clone()
- Files.copy() (Correct answer)
- Files.transfer()
Correct answer: Files.copy()
Files.copy() copies a file from a source Path to a target Path and accepts optional CopyOption flags such as REPLACE_EXISTING.
Which interface in Java NIO.2 (introduced in Java 7) represents a path to a file or directory on the file system?