OCJP Practice Papers - Java File I/O Nio.2
OCJP Practice Papers Java File I/O NIO.2 include following topics
- Use Path interface to operate on file and directory paths
- Use Files class to check, read, delete, copy, move, manage metadata of a file ordirectory
- Use Stream API with NIO.2
See the complete syllabus for OCJP here
- Fill in the blanks: A(n)____ is a file that contains a reference to another file
or directory, while a(n)____ is a file that contains content.
A. irregular file, regular file
B. regular file, opaque file
C. symbolic link, regular file
D. symbolic link, symbolic directory
2. Which methods listed below are found in the NIO.2 Path interface?
I. getRoot()
II. isDirectory()
III. listFiles()
IV. toRealPath()
A. I only
B. I, II, and III
C. I and IV
D. II and III
3. Assuming the file /secret/hide.txt exists and is marked hidden, what is result of
executing the following program?
package hidden;
import java.nio.file.*;
public class Finder {
public void findHiddenFile(Path p) throws Exception {
if(File.isHidden(p)) {
System.out.print("Found!");
}
}
public static void main(String[] folders) throws Exception {
final Finder f = new Finder();
f.findHiddenFile(Paths.get("/secret/hide.txt"));
}
}
A. The class does not compile.
B. An exception is printed at runtime.
C. Found! is printed at runtime.
D. Nothing is printed at runtime.
4. Fill in the blanks: Files.walk() performs a __________ traversal, while
Files.find() performs a __________ traversal.
A. breadth-first, breadth-first
B. breadth-first, depth-first
C. depth-first, breadth-first
D. depth-first, depth-first
5. When reading file information, what is an advantage of using an NIO.2 attribute
interface rather than reading the values individually from Files methods?
A. Costs fewer round-trips to the file system
B. Guarantees performance improvement
C. Has support for symbolic links
D. Reduces memory leaks
6. What is the result of compiling and executing the following program? Assume the
current directory is /stock and the path /stock/sneakers does not exist prior to
execution.
package shoe;
import java.io.*;
import java.nio.file.*;
public class Sneaker {
public void setupInventory(Path desiredPath) throws Exception {
Path suggestedPath = Paths.get("sneakers");
if(Files.isSameFile(suggestedPath, desiredPath) // j1
&& !Files.exists(suggestedPath))
Files.createDirectories(desiredPath); // j2
}
public static void main(String[] socks) throws Exception {
Path w = new File("/stock/sneakers").toPath(); // j3
new Sneaker().setupInventory(w);
}
}
A. The directory /stock/sneakers is created.
B. Line j1 does not compile or produces an exception at runtime.
C. Line j2 does not compile or produces an exception at runtime.
D. Line j3 does not compile or produces an exception at runtime.
7. Assuming the path referenced below exists and contains a symbolic link that
references /again, what is the expected result of executing the following code snippet?
System.out.print(Files.walk(Paths.get("/again/and/again")).count());
A. An exception is thrown at runtime.
B. A number is printed at runtime.
C. The process hangs indefinitely.
D. The result cannot be determined with the information given.
8. Which method in the NIO.2 Files class is equivalent to the java.io.File method
length()?
A. length()
B. size()
C. getLength()
D. None of the above
9. Assuming the current working directory is /home, then what is the output of the
following program?
1: package magic;
2: import java.nio.file.*;
3: public class Magician {
4: public String doTrick(Path path) {
5: return path.subpath(2,3)
6: .getName(1)
7: .toAbsolutePath()
8: .toString();
9: }
10: public static void main(String... cards) {
11: final Magician m = new Magician();
12: System.out.print(m.doTrick(
13: Paths.get("/bag/of/tricks/.././disappear.txt")));
14: } }
A. /home/tricks
B. /home
C. The code does not compile.
D. The code compiles but prints an exception at runtime.
10. Which methods listed below are found in the NIO.2 Files class?
I. isSameFile()
II. length()
III. relativize()
IV. mkdir()
A. I only
B. I, II, and IV
C. II and III
D. IV only
11. The following code snippet, which attempts to move a file system record from
oldHardDrivePath to newHardDrivePath, results in an exception at runtime. Which of
the following is the most likely type of exception to be thrown?
Files.move(oldHardDrivePath,newHardDrivePath,REPLACE_EXISTING);
A. AtomicMoveNotSupportedException
B. DirectoryNotEmptyException
C. FileAlreadyExistsException
D. None of the above since the line of code does not compile
12. Which of the following can be filled into the blank that would allow the method to
compile?
public String getPathName(String fileName) {
final Path p = ____________________;
return p.getFileName();
}
I. new File(fileName).toPath()
II. new Path(fileName)
III. FileSystems.getDefault().getPath(fileName)
A. I and II
B. I and III
C. II
D. None of the above
13. Which statement about the following class is correct?
package clone;
import java.io.*;
import java.nio.file.*;
public class Rewriter {
public static void copy(Path source, Path target) throws Exception {
try (BufferedReader r = Files.newBufferedReader(source);
Writer w = Files.newBufferedWriter(target)) {
String temp = null;
while((temp = r.readLine()) != null) {
w.write(temp);
}
}
}
public static void main(String[] tooMany) throws Throwable {
Rewriter.copy(Paths.get("/original.txt"),
FileSystems.getDefault().getPath("/","unoriginal.txt"));
}
}
A. The class compiles without issue.
B. The class never throws an exception at runtime.
C. The implementation correctly copies a regular file.
D. All of the above
14. Fill in the blanks: The Files.__________ method returns a List, while the
Files.__________ method returns a Stream.
A. lines(), readAllLines()
B. lines(), readLines()
C. readAllLines(), lines()
D. readLines(), lines()
15. What is the output of the following application?
1: package yellow;
2: import java.nio.file.*;
3: public class Road {
4: public boolean findHome() {
5: Path oftenTraveled = Paths.get("/highway/street/spot.txt");
6: Path lessTraveled = Paths.get("/highway/street/house/../.");
7: lessTraveled.resolve("spot.txt");
8: return oftenTraveled.equals(lessTraveled.normalize());
9: }
10: public static void main(String... emerald) {
11: System.out.print("AM I HOME? "
12: +(new Road().findHome() ? "yes" : " no"));
13: }
14: }
A. AM I HOME? no
B. AM I HOME? yes
C. The class does not compile.
D. The class compiles but throws an exception at runtime.
16. Which of the following is not an advantage of using an NIO.2 Path instead of a
java.io.File to work with files?
A. Contains built-in support for symbolic links
B. Has ability to read operating-system-specific attributes
C. Provides a single method for deleting a directory tree
D. Provides efficient access of file metadata
17. What is the result of executing the following program? Assume the path /driveway
exists and is non-empty, and the directory tree is fully accessible within the file
system.
package weather;
import java.io.*;
import java.nio.file.*;
public class Snow {
public static boolean removeSnow(Path flake) throws IOException {
if(!Files.isDirectory(flake) && !Files.isSymbolicLink(flake))
return Files.delete(flake);
else return true;
}
public static void main(String[] cones) throws IOException {
File driveway = new File("/driveway");
for(File f : driveway.listFiles()) {
System.out.println(removeSnow(f.toPath()));
}
}
}
A. The program prints a list of only true values.
B. The program prints a mix of true and false values.
C. The code does not compile.
D. The code compiles but prints an exception at runtime.
18. Which interface name inserted into the blank below allows the code snippet to
compile?
Path file = Paths.get("/data/movie.txt");
BasicFileAttributes b = Files.readAttributes(file, __________);
A. BasicFileAttributes.class
B. DosFileAttributes.class
C. PosixFileAttributes.class
D. All of the above
19. What is the output of the following code snippet? Assume that the current directory is
the root path.
Path p1 = Paths.get("./locks");
Path p2 = Paths.get("/found/red.zip");
System.out.println(p1.relativize(p2));
System.out.println(p2.relativize(p1));
A. ../found/red.zip
../../locks
B. ../../locks
../found/red.zip
C. locks/../found/red.zip
../found/locks
D. None of the above
20. What is the output of the following code snippet? Assume that the current directory is
the root path.
Path p1 = Paths.get("./found/../keys");
Path p2 = Paths.get("/lost/blue.txt");
System.out.println(p1.resolve(p2));
System.out.println(p2.resolve(p1));
A. /lost/blue.txt
./found/../keys
B. /found/../keys/./lost/blue.txt
/lost/blue.txt/keys
C. /lost/blue.txt
/lost/blue.txt/./found/../keys
D. None of the above
21. What is the output of the following application? Assume the application is called with
a valid path that exists and is accessible within the file system.
package charity;
import java.nio.file.*;
public class Roster {
protected void printRoster(Path p) {
for(Path f : Files.list(p)) { // n1
if(f.toString().endsWith(".per")) // n2
System.out.print(f);
}
}
public static void main(String... volunteers) {
new Roster().printRoster(Paths.get(volunteers[0]));
}
}
A. A list of file names is printed at runtime.
B. The class does not compile due to line n1.
C. The class does not compile due to line n2.
D. None of the above
22. Given the following file system diagram, in which forward is a symbolic link to the
java directory, which value does not print /java/Sort.java at runtime?
Path p = Paths.get("/", "objC", "bin");
System.out.println(p.resolve("__________").toRealPath());
A. ../backwards/../forward/Sort.java
B. ../forward/./Sort.java
C. ../java/./forward/Sort.java
D. ../../java/Sort.java
23. Using the file system diagram from the previous question, including the symbolic link
from forward to java, how many calls to Files.delete() would need to be made
before the following line could be executed without throwing an exception?
Files.delete(Paths.get("/objC"));
A. One
B. Four
C. Seven
D. None of the above. The symbolic link needs to be removed with
Files.deleteSymbolicLink() first.
24. Assuming the course.txt file exists and is readable, what is the result of executing the
following application?
package schoolwork;
import java.io.*;
import java.nio.file.*;
public class Notes {
public void printNotes() {
try (OutputStream out = System.out) { // y1
Files.copy(out, Paths.get("course.txt"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] coursework) {
new Notes().printNotes();
}
}
A. The code compiles but prints an exception at runtime.
B. The class does not compile due to line y1.
C. The code does not compile for some other reason.
D. The program prints the contents of the course.txt file.
25. When reading file information, what is an advantage of loading a
BasicFileAttributeView over a BasicFileAttributes?
A. Allows the hidden attribute to be set
B. Allows the last modified date to be changed
C. All of the file information is read in a single round-trip.
D. There is no advantage.
26. The Rose application is run with an input argument of /flower. The /flower directory
contains five subdirectories, each of which contains five files. How many Path values
does the following application print?
import java.nio.file.*;
public class Rose {
public void tendGarden(Path p) throws Exception {
Files.walk(p,1)
.map(p - p.toRealPath())
.forEach(System.out::println);
}
public static void main(String... thorns) throws Exception {
new Rose().tendGarden(Paths.get(thorns[0]));
}
}
A. None
B. One
C. Six
D. Thirty-one
27. Which of the following statements, when run independently, produces a
NullPointerException at runtime?
I. Paths.get("../sang").getParent().getParent()
II. Paths.get("/sing").getParent().getRoot()
III. Paths.get("/song").getRoot().getRoot()
IV. Paths.get("../sung").getRoot().getParent()
A. I and III
B. I and IV
C. II and III
D. IV only
28. Which statement about the following Finalize class is correct?
1: package end;
2: import java.nio.file.*;
3: public class Finalize {
4: public Path makeAbsolute(Path p) {
5: if(p!=null && !p.isAbsolute())
6: return p.toAbsolutePath();
7: return p;
8: }
9: }
A. It does not compile because IOException is neither handled nor declared.
B. It does not compile for some other reason.
C. The method compiles and returns a Path value that is always equivalent to the
input argument.
D. The method compiles and returns a Path value that may not be equivalent to the
input argument.
29. Which of the following is a difference between the createDirectory() and
createDirectories() methods found in the NIO.2 Files class?
A. One takes multiple Path arguments; the other does not.
B. One throws an exception if a file already exists at the directory path; the other does
not.
C. One declares a checked exception; the other does not.
D. One creates a single directory while the other may create many directories.
30. Assuming the current working directory is /hail, what is the expected output of
executing the following code snippet?
Path w1 = Paths.get("../jungle/.././rain..")
.toAbsolutePath().normalize();
System.out.print(w1.resolve("snow.txt"));
A. /jungle/snow.txt
B. /hail/rain../snow.txt
C. /rain../snow.txt
D. An exception is printed at runtime.
31. What is the output of the following application?
package med;
import java.nio.file.*;
public class Surgeon {
public Path rebuild(Path p) {
Path v = null;
for(int i=0; ip.getNameCount(); i++)
if(v==null) v = p.getName(i);
else v = v.resolve(p.getName(i));
return v;
}
public static void main(String... tools) {
final Surgeon al = new Surgeon();
Path original = Paths.get("/tissue/heart/chambers.txt");
Path repaired = al.rebuild(original);
System.out.print(original.equals(repaired));
}
}
A. false
B. true
C. The code does not compile.
D. The code compiles but prints an exception at runtime.
32. Under which circumstances does Files.deleteIfExists() not throw an exception?
A. The file system suddenly becomes unavailable.
B. The path does not exist.
C. The path represents a non-empty directory.
D. The process does not have write access to a path.
33. What is the output of the following code snippet? Assume all referenced paths exist
within the file system.
Path v1 = Path.get("/./desert/./").resolve(Paths.get("sand.doc"));
Path v2 = new File("/desert/./cactus/../sand.doc").toPath();
System.out.print(Files.isSameFile(v1,v2));
System.out.print(" "+v1.equals(v2));
System.out.print(" "+v1.normalize().equals(v2.normalize()));
A. false false false
B. true false true
C. true true true
D. None of the above
34. How many lines of the following program contain compilation errors?
public class Song {
public static void organize(Path folder, Path file) throws IOException {
Path p = folder.resolve(file);
BasicFileAttributeView vw = Files.getFileAttributeView(p,
BasicFileAttributes.class);
if(vw.creationTime().toMillis()System.currentTimeMillis()) {
vw.setTimes(FileTime.fromMillis(System.currentTimeMillis()),
null,null);
}
}
public static void main(String[] audio) throws Exception {
Song.organize(Paths.get("/", "pub"),new File("/songs").toPath());
}
}
A. None
B. One
C. Two
D. Three
35. What is the output of the following application?
package stars;
import java.nio.file.*;
public class Sun {
public void printInfo() {
Path halleysComet = Paths.get("stars/./rocks/../m1.meteor")
.normalize();
Path lexellsComet = Paths.get("./stars/../solar/");
lexellsComet = lexellsComet.subpath(0, 2)
.resolve("m1.meteor")
.normalize();
System.out.print(halleysComet.equals(lexellsComet)
? "Same!" : "Different!");
}
public static void main(String... emerald) {
Sun s = new Sun();
s.printInfo();
}
}
A. Different!
B. Same!
C. The class does not compile.
D. The class compiles but throws an exception at runtime.
36. Assuming the directory /eclipse/projects exists and its contents are accessible,
which statement about the following code snippet is correct?
Path p = Paths.get("/eclipse/projects");
Files.walk(p)
.map(z - z.toAbsolutePath().toString())
.filter(s - s.endsWith(".java"))
.collect(Collectors.toList()).forEach(System.out::println);
Files.find(p,Integer.MAX_VALUE,
(w,a) - w.toAbsolutePath().toString().endsWith(".java"))
.collect(Collectors.toList()).forEach(System.out::println);
A. The first stream statement does not compile.
B. The second stream statement does not compile.
C. Both statements compile but are unlikely to print the same results at runtime.
D. None of the above
37. Assuming the file referenced below exists and is significantly large, which statement
about the following program is correct?
public class SpeedRead {
public void jenniferReads(Path p) {
Files.lines(p);
}
public void jonReads(Path p) {
Files.readAllLines(p);
}
public static void main(String[] pages) {
Path p = Paths.get("/bookshelf/mobydick.txt");
final SpeedRead r = new SpeedRead();
r.jenniferReads(p);
r.jonReads(p);
}
}
A. The code does not compile.
B. The method jenniferReads() is likely to take longer to run.
C. The method jonReads() is likely to take longer to run.
D. It is not possible to know which method will take longer to run.
38. What is the result of executing the following program? Assume the files referenced in
the application both exist and are fully accessible within the file system.
package duplicate;
import static java.nio.file.StandardCopyOption.*;
import static java.nio.file.Files.*;
import java.io.*;
import java.nio.file.*;
public class CopyOfACopy {
public void main(String[] items) throws Exception {
final Path s = new File("apples.zip").toPath();
final Path t = FileSystems.getDefault().getPath("oranges.zip");
copy(s,t,REPLACE_EXISTING); // q1
copy(Files.newBufferedReader(t),t,ATOMIC_MOVE); // q2
}
}
A. Line q1 does not compile.
B. Line q1 produces an exception at runtime.
C. Line q2 does not compile.
D. Line q2 produces an exception at runtime.
39. Which of the following Files methods requires the enclosing method to handle or
declare a checked exception?
A. exists()
B. isDirectory()
C. isSameFile()
D. isSymbolicLink()
40. What is the output of the following application? Assume /all-data exists and is
accessible within the file system.
package numbers;
import java.nio.file.*;
import java.util.stream.Stream;
public class TheCount {
public static StreamString readLines(Path p) {
try {
return Files.lines(p);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static long count(Path p) throws Exception {
return Files.list(p)
.filter(w - Files.isRegularFile(w))
.flatMap(s - readLines(s))
.count();
}
public final static void main(String[] day) throws Exception {
System.out.print(count(Paths.get("/all-data")));
}
}
A. The number of lines in all files in a directory tree
B. The number of lines in all files in a single directory
C. The code does not compile.
D. The code compiles but prints an exception at runtime.
OCJP Practice Test, Certification Path, Tips/Tricks
- Oracle (OCJP) Java Certification Exam
- Java Certification Tips And Tricks
- OCJP Practice Papers - Java Basics
- OCJP Practice Papers - Operators And Decision Constructs
- OCJP Practice Papers-A Advanced Java Class Design
- OCJP Practice Papers Creating And Using Arrays
- OCJP Practice Papers Using Loop Constructs
- OCJP Practice Papers - Generics And Collections
- OCJP Practice Papers - Lambda Built-In Functional Interfaces
- OCJP Practice Papers Java Class Design
- OCJP Practice Papers - Java Stream API
- OCJP Practice Papers - Exceptions And Assertions
- OCJP Practice Papers - Date/Time API
- OCJP Practice Papers - Java I/O Fundamentals
- OCJP Practice Papers - Working With Methods And Encapsulation
- OCJP Practice Papers - Working With Inheritance
- OCJP Practice Papers - Handling Exceptions
- OCJP Practice Papers - Selected Classes From Java API
- OCJP Practice Papers - Java File I/O Nio.2
- OCJP Practice Papers - Java Concurrency