THE OCP EXAM TOPICS COVERED IN THIS PRACTICE TEST INCLUDE THE FOLLOWING:
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.
Which methods listed below are found in the NIO.2 Path interface?
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"));
}
}
Fill in the blanks: Files.walk() performs a __________ traversal, while Files.find() performs a __________ traversal.
When reading file information, what is an advantage of using an NIO.2 attribute interface rather than reading the values individually from Files methods?
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);
}
}
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());
Which method in the NIO.2 Files class is equivalent to the java.io.File method length()?
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: } }
Which methods listed below are found in the NIO.2 Files class?
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);
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();
}
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"));
}
}
Fill in the blanks: The Files.__________ method returns a List, while the Files.__________ method returns a Stream.
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: }
Which of the following is not an advantage of using an NIO.2 Path instead of a java.io.File to work with files?
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()));
}
}
}
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, __________);
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));
../found/red.zip
../../locks
../../locks
../found/red.zip
locks/../found/red.zip
../found/locks
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));
/lost/blue.txt
./found/../keys
/found/../keys/./lost/blue.txt
/lost/blue.txt/keys
/lost/blue.txt
/lost/blue.txt/./found/../keys
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]));
}
}
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());
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"));
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();
}
}
When reading file information, what is an advantage of loading a BasicFileAttributeView over a BasicFileAttributes?
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]));
}
}
Which of the following statements, when run independently, produces a NullPointerException at runtime?
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: }
Which of the following is a difference between the createDirectory() and createDirectories() methods found in the NIO.2 Files class?
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"));
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; i<p.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));
}
}
Under which circumstances does Files.deleteIfExists() not throw an exception?
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()));
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());
}
}
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();
}
}
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);
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);
}
}
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
}
}
Which of the following Files methods requires the enclosing method to handle or declare a checked exception?
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 Stream<String> 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")));
}
}