Free Java 17 1Z0-829 Practice Questions: Using Java I/O API
Practice 10 free Oracle Java SE 17 Developer (Java 17 1Z0-829) questions on Using Java I/O API, with answers, explanations, and the IT Mastery next step.
Try the IT Mastery web app for a richer interactive practice experience with mixed sets, timed mocks, topic drills, explanations, and progress tracking.
Topic snapshot
| Field | Detail |
|---|---|
| Practice target | Java 17 1Z0-829 |
| Topic area | Using Java I/O API |
| Blueprint weight | 6% |
| Page purpose | Focused sample questions before returning to mixed practice |
How to use this topic drill
Use this page to isolate Using Java I/O API for Java 17 1Z0-829. Work through the 10 questions first, then review the explanations and return to mixed practice in IT Mastery.
| Pass | What to do | What to record |
|---|---|---|
| First attempt | Answer without checking the explanation first. | The fact, rule, calculation, or judgment point that controlled your answer. |
| Review | Read the explanation even when you were correct. | Why the best answer is stronger than the closest distractor. |
| Repair | Repeat only missed or uncertain items after a short break. | The pattern behind misses, not the answer letter. |
| Transfer | Return to mixed practice once the topic feels stable. | Whether the same skill holds up when the topic is no longer obvious. |
Blueprint context: 6% of the practice outline. A focused topic score can overstate readiness if you recognize the pattern too quickly, so use it as repair work before timed mixed sets.
Sample questions
These are original IT Mastery practice questions aligned to this topic area. They are not official Oracle questions, copied live-exam content, or exam dumps. Use them to preview question style and explanation depth before continuing with topic drills, mixed sets, and timed mocks in IT Mastery.
Question 1
Topic: Using Java I/O API
Assume p and q are Path objects for two different existing regular files, and the process has the needed permissions. Which Java 17 NIO.2 statement is true?
Options:
A.
Files.writeString(p, "x", StandardOpenOption.CREATE_NEW)throwsFileAlreadyExistsException.B.
Files.move(q, p)replacespby default.C.
Files.writeString(p, "x", StandardOpenOption.APPEND)truncatespbefore writing.D.
Files.copy(q, p)replacespby default.
Best answer: A
Explanation: CREATE_NEW is the create-only option: it succeeds only when the file does not already exist. For an existing regular file, Files.writeString() with CREATE_NEW fails rather than appending or overwriting.
NIO.2 separates create, append, and replace behavior through options. StandardOpenOption.CREATE_NEW means create a new file atomically and fail if the file already exists. By contrast, APPEND writes to the end of an existing file, while Files.copy() and Files.move() do not replace an existing target unless StandardCopyOption.REPLACE_EXISTING is supplied. The key rule is that replacement is not the default for copy or move operations.
- Append confusion fails because
APPENDwrites at the end of the existing file; it does not truncate first. - Copy replacement fails because
Files.copy(q, p)needsREPLACE_EXISTINGwhenpalready exists. - Move replacement fails because
Files.move(q, p)also needsREPLACE_EXISTINGto replace an existing target.
Question 2
Topic: Using Java I/O API
A developer is troubleshooting a utility that must display attributes of a symbolic link itself, not its target. The file system supports symbolic links. logs/current.log is a symbolic link to logs/app.log, and logs/app.log is a regular file of size 1,024 bytes. The code compiles but reports attributes for the target file.
Path p = Path.of("logs/current.log");
BasicFileAttributes a =
Files.readAttributes(p, BasicFileAttributes.class);
System.out.println(a.isSymbolicLink());
System.out.println(a.isRegularFile());
System.out.println(a.size());
Which next fix best matches the intended behavior?
Options:
A. Call
p.normalize()before reading attributes.B. Add
LinkOption.NOFOLLOW_LINKStoreadAttributes.C. Use
p.toRealPath()before reading attributes.D. Replace
BasicFileAttributeswithPosixFileAttributes.
Best answer: B
Explanation: NIO.2 file attribute reads follow symbolic links by default. To inspect the symbolic link itself, pass LinkOption.NOFOLLOW_LINKS to Files.readAttributes() so the returned BasicFileAttributes describe the link rather than its target.
The core issue is symbolic link handling in NIO.2 attribute reads. Files.readAttributes(path, BasicFileAttributes.class) follows links unless told otherwise, so the attributes describe logs/app.log. Adding LinkOption.NOFOLLOW_LINKS changes the lookup to the link object at logs/current.log, allowing isSymbolicLink() to reflect the link itself.
The fixed call is:
BasicFileAttributes a = Files.readAttributes(
p, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
Path cleanup or choosing a more specific attribute interface does not change the default link-following behavior.
- Path normalization only removes redundant name elements; it does not affect symbolic link traversal.
- Real path lookup typically resolves the link to its target, which is the opposite of the intent.
- POSIX attributes add owner, group, and permission data where supported, but they still follow links unless
NOFOLLOW_LINKSis used.
Question 3
Topic: Using Java I/O API
In Java 17 default object serialization, assume a class implements java.io.Serializable, declares private static final long serialVersionUID = 1L;, and has no custom serialization methods or serialPersistentFields. Which statement is true?
Options:
A.
transientinstance fields are serialized if their types implementSerializable.B. The serializable class’s constructor runs before its fields are restored.
C.
serialVersionUIDis restored as part of the object’s instance state.D. Default serializable fields are non-static, non-transient fields; the UID is checked.
Best answer: D
Explanation: Default serialization does not save every field. For a Serializable class without custom serialization, the serializable fields are the non-static, non-transient instance fields. The declared serialVersionUID is used for compatibility checking during deserialization, not as normal object state.
Java’s default serialization stores object state using the class’s default serializable fields: instance fields that are not transient. Static fields are class state, not instance state, and transient fields are intentionally skipped. A declared serialVersionUID is a class version identifier used when reading the stream; if the stream’s UID and the local class’s UID do not match, deserialization can fail with InvalidClassException. It is not restored like an ordinary field. Also, constructors of serializable classes are not run during normal deserialization; construction rules apply differently through the first non-serializable superclass.
- Transient type trap fails because
transientskips the field regardless of whether its type implementsSerializable. - UID as state fails because
serialVersionUIDis used in the class descriptor compatibility check, not restored as instance data. - Constructor assumption fails because a serializable class’s constructor is not normally invoked during deserialization.
Question 4
Topic: Using Java I/O API
Assume the temporary file can be created. What is the result of running this Java 17 program?
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
public class ReadInfo {
public static void main(String[] args) throws Exception {
Path p = Files.createTempFile("exam", ".txt");
try {
Files.writeString(p, "notes");
BasicFileAttributes attrs =
Files.readAttributes(p, BasicFileAttributes.class);
System.out.print(attrs.isRegularFile() + ":" +
attrs.isDirectory() + ":" + attrs.size());
} finally {
Files.deleteIfExists(p);
}
}
}
Options:
A.
true:false:5B.
false:true:5C. The code does not compile.
D.
true:false:0
Best answer: A
Explanation: Files.readAttributes() can read BasicFileAttributes for a Path. The created path is a regular file, and after Files.writeString() writes "notes", the basic size attribute is 5 bytes.
The core NIO.2 concept is reading file metadata with Files.readAttributes(path, BasicFileAttributes.class). Files.createTempFile() creates a regular file, not a directory. Files.writeString() writes the supplied character data to that file and closes it before the next statement runs. Since "notes" contains only ASCII characters, its UTF-8 representation is 5 bytes, so attrs.size() returns 5 for this regular file.
The key takeaway is that BasicFileAttributes reports properties of the file referenced by the Path; it is not a directory attribute view and it does not require opening a stream manually.
- Empty file assumption fails because
Files.writeString()writes and closes the file before attributes are read. - Directory assumption fails because
Files.createTempFile()creates a regular file. - Compilation concern fails because
BasicFileAttributesis imported and is a valid target type forFiles.readAttributes().
Question 5
Topic: Using Java I/O API
Assume the file operations succeed and the temporary directory is initially empty. What is the result of running this Java 17 code?
import java.nio.file.*;
import java.util.stream.Stream;
public class Scan {
public static void main(String[] args) throws Exception {
Path root = Files.createTempDirectory("exam");
Files.createDirectories(root.resolve("src/main"));
Files.writeString(root.resolve("src/A.txt"), "a");
Files.writeString(root.resolve("src/main/B.txt"), "b");
try (Stream<Path> paths = Files.walk(root, 2)) {
long count = paths.filter(Files::isRegularFile).count();
System.out.print(count);
}
}
}
Options:
A. It prints
0.B. It does not compile because
Stream<Path>is not closeable.C. It prints
2.D. It prints
1.
Best answer: D
Explanation: The code compiles and prints 1. Files.walk(root, 2) traverses the starting path at depth 0 and descendants through depth 2, so src/A.txt is counted but src/main/B.txt is too deep.
Files.walk returns a Stream<Path> that should be closed after use, commonly with try-with-resources. Its maxDepth is measured from the starting path: root is depth 0, src is depth 1, and both src/A.txt and src/main are depth 2. The file src/main/B.txt is depth 3, so it is not visited by Files.walk(root, 2).
The filter counts only regular files among the visited paths, leaving only src/A.txt. Stream extends BaseStream, which extends AutoCloseable, so using it in try-with-resources is valid and closes the directory traversal resources.
- All descendants is wrong because
maxDepthlimits how farwalkdescends. - Directories only is wrong because
Files.walkcan visit both files and directories within the depth limit. - Not closeable is wrong because
Stream<Path>is usable in try-with-resources.
Question 6
Topic: Using Java I/O API
A Java SE 17 NIO.2 question shows this code and gives no operating system or file-system details:
Path p = Path.of("logs", "app.txt");
System.out.println(p);
Which rule should guide the answer?
Options:
A. The printed separator is platform-dependent.
B. The printed separator is always
\.C. The call fails if
logsis missing.D. The printed separator is always
/.
Best answer: A
Explanation: Path is an abstraction over a file-system provider. When the platform or file system is not specified, an exam answer should not depend on Unix-style or Windows-style separators in the printed path.
In NIO.2, Path.of("logs", "app.txt") builds a Path object using the default file system. The exact string form produced by System.out.println(p) comes from p.toString(), and separator syntax is provider/platform dependent. Java does not guarantee that this prints with / or with \ in a platform-neutral question.
Creating the Path also does not check that the file or directory exists. Existence checks happen with APIs such as Files.exists() or actual file operations.
- Forward slash output assumes a Unix-like file system, which is not guaranteed by Java SE.
- Backslash output assumes Windows-style rendering, which is also not guaranteed.
- Missing directory failure confuses path construction with file access;
Path.ofdoes not require the path to exist.
Question 7
Topic: Using Java I/O API
A Java 17 batch job normalizes a text file. source already exists; target and backup may be in directories that do not exist yet; backup may already exist; temp may or may not exist. normalize() returns a String. The job must read and write UTF-8, replace target content, copy the normalized target to backup replacing any old backup, and ignore a missing temp file.
Which replacement best fixes the body?
Path source = Path.of("in", "raw.txt");
Path target = Path.of("out", "daily", "clean.txt");
Path backup = Path.of("out", "backup", "clean.txt");
Path temp = Path.of("out", "daily", "clean.tmp");
Files.createDirectory(target.getParent());
var text = Files.readString(source);
Files.writeString(target, normalize(text));
Files.copy(target, backup);
Files.delete(temp);
Options:
A. Use
createDirectoryfor both parents, UTF-8readString/writeString, plaincopy, andif (Files.exists(temp)) Files.delete(temp).B. Use
createDirectoriesfor both parents, UTF-8readString/writeStringwith create/truncate,copy(..., REPLACE_EXISTING), anddeleteIfExists.C. Use
createDirectories(target)andcreateDirectories(backup), then UTF-8readString/writeString,copy(..., REPLACE_EXISTING), anddeleteIfExists.D. Use
createDirectoriesfor both parents, UTF-8readString/writeString,move(target, backup, REPLACE_EXISTING), anddeleteIfExists.
Best answer: B
Explanation: The best fix uses NIO.2 Files methods that match each required operation. createDirectories handles missing parent directories, explicit UTF-8 methods handle text, REPLACE_EXISTING handles an old backup, and deleteIfExists handles an optional temp file.
For directory setup, Files.createDirectories(path) is the appropriate method when one or more directories in the path may be missing. The code must create the parent directories, not the file paths themselves. Files.readString and Files.writeString can use StandardCharsets.UTF_8; write options such as CREATE, TRUNCATE_EXISTING, and WRITE make the replacement behavior explicit. Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING) is needed because the backup may already exist. Files.deleteIfExists(temp) matches the requirement to ignore a missing temp file.
The key distinction is choosing the Files method and option that matches the file-system condition stated in the scenario.
- Single-directory creation fails because
createDirectorydoes not create missing intermediate directories and throws if the directory already exists. - Wrong path creation fails because
createDirectories(target)would create a directory namedclean.txt, not the parent directory for the file. - Move instead of copy fails because moving
targettobackupremoves the normalized target file.
Question 8
Topic: Using Java I/O API
On a Unix-like file system, a logging setup should combine a base directory with a configured log path that is intended to be relative to that base. The expected parent is /srv/app/logs, but the diagnostic prints /|/logs|app.log.
import java.nio.file.*;
public class PathsDemo {
public static void main(String[] args) {
Path base = Path.of("/srv/app");
Path input = Path.of("/logs/../logs/app.log");
Path p = base.resolve(input).normalize();
System.out.println(p.getRoot() + "|" + p.getParent() + "|" + p.getFileName());
}
}
Which change best fixes the cause?
Options:
A. Call
input.normalize()beforeresolve.B. Replace
resolvewithrelativize.C. Call
base.toAbsolutePath()beforeresolve.D. Remove the leading slash from
input.
Best answer: D
Explanation: resolve does not always append; if the argument is absolute, it returns that argument. The leading slash makes input absolute, so normalization removes .. but does not reattach /srv/app. Making input relative lets resolve form the intended path before getParent and getFileName inspect it.
In NIO.2, Path.resolve(other) appends other only when other is relative. If other has a root, such as / on a Unix-like system, resolve returns other. Here, input starts with /, so p normalizes to /logs/app.log; getRoot() is /, getParent() is /logs, and getFileName() is app.log. Removing the leading slash makes the configured path relative, so base.resolve(input).normalize() becomes /srv/app/logs/app.log. relativize computes a path between two paths, and toAbsolutePath does not force an absolute right operand to be appended.
- Absolute base fails because making
baseabsolute does not change howresolvetreats an absoluteinput. - Normalize first fails because
/logs/../logs/app.logstill has the Unix root/after normalization. - Relativize instead fails because
relativizecomputes a path between locations; it is not a path-joining operation.
Question 9
Topic: Using Java I/O API
A service must store an uploaded file under /srv/uploads, preserving only the final file name from the client path. On a Unix-like default file system, assume:
Path base = Path.of("/srv/uploads");
Path incoming = Path.of("/tmp/client/a.txt");
Which expression produces the Path /srv/uploads/a.txt without checking whether any file exists?
Options:
A.
base.relativize(incoming).normalize()B.
base.resolve(incoming.getFileName())C.
incoming.resolve(base).getFileName()D.
base.resolve(incoming)
Best answer: B
Explanation: Path operations such as resolve() and getFileName() are lexical and do not require the file to exist. Since incoming is absolute, resolving it directly would ignore base; first extract its final name, then resolve that name against the target directory.
The key rule is that Path.resolve(other) returns other when other is absolute. Here, incoming is /tmp/client/a.txt, so base.resolve(incoming) would not put the file under /srv/uploads. incoming.getFileName() returns the last name element, a.txt, which is a relative path. Resolving that relative path against /srv/uploads yields /srv/uploads/a.txt.
These NIO.2 path methods operate on path strings; they do not verify that directories or files exist. The important distinction is absolute path resolution versus resolving a relative file name.
- Absolute right operand fails because resolving
/tmp/client/a.txtagainstbasereturns the absolute incoming path. - Reversed resolve fails because resolving an absolute
baseagainstincomingreturns/srv/uploads, whose file name isuploads. - Relativize direction fails because it computes a relative path from
/srv/uploadsto/tmp/client/a.txt, not a target storage path.
Question 10
Topic: Using Java I/O API
Which statement about Java 17 java.nio.file.Path behavior is correct?
Options:
A.
normalize()works lexically without checking file existence.B.
relativize()accepts any mix of absolute and relative paths.C.
toAbsolutePath()always removes.and..elements.D.
resolve()appends the right-hand path even if it is absolute.
Best answer: A
Explanation: Path.normalize() is a lexical operation. It simplifies redundant path name elements where possible, but it does not verify that files or directories exist and does not account for symbolic links.
The key NIO.2 rule is that many Path methods operate on path names, not on file-system contents. normalize() removes redundant . elements and collapses reducible name/.. pairs without touching the disk. This can change the apparent path text, but it does not prove that the resulting path exists or refers to the same file through symbolic links.
toAbsolutePath() makes a path absolute but does not guarantee normalization. resolve() returns the right-hand path when that path is absolute. relativize() requires compatible paths, such as both relative or both absolute with compatible roots.
- Automatic cleanup fails because
toAbsolutePath()is not the same operation asnormalize(). - Absolute resolve fails because an absolute right-hand path replaces the base path.
- Mixed relativize fails because incompatible absolute and relative paths cannot form a relative path.
Continue in the web app
Use IT Mastery for interactive Java 17 1Z0-829 practice with mixed sets, timed mocks, topic drills, explanations, and progress tracking.
Related focused pages
- Free Java 17 1Z0-829 Full-Length Practice Exam
- Core Value Types
- Controlling Program Flow
- Object-Oriented Java
- Handling Exceptions
- Working with Arrays and Collections
- Streams and Lambdas
- Packaging and Modules
- Managing Concurrent Code Execution
- Accessing Databases Using JDBC
- Implementing Localization
- Logging and Annotations