Programmer II Chapter 9: NIO.2 Flashcards

1
Q

What is the output of the following code?

 4: var path = Path.of("/user/./root","../kodiacbear.txt");
 5: path.normalize().relativize("/lion");
 6: System.out.println(path); 
A. ../../lion
B. /user/kodiacbear.txt
C. ../user/kodiacbear.txt
D. /user/./root/../kodiacbear.txt
E. The code does not compile.
F. None of the above
A
E. 
The relativize() method takes a Path value, not a String. For this reason, line 5 does notcompile, and option E is correct. If line 5 was corrected to use a Path value, then the code wouldcompile, but it would print the value of the Path created on line 4. Since Path is immutable, theoperations on line 5 are not saved anywhere. For this reason, option D would be correct. Finally, if thevalue on line 5 was assigned to path and printed on line 6, then option A would be correct.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

For which values of path sent to this method would it be possible for the following code to output Success? (Choose all that apply.)

 public void removeBadFile(Path path) {
    if(Files.isDirectory(path))
       System.out.println(Files.deleteIfExists(path)
           ? "Success": "Try Again");
 }

A. path refers to a regular file in the file system.
B. path refers to a symbolic link in the file system.
C. path refers to an empty directory in the file system.
D. path refers to a directory with content in the file system.
E. path does not refer to a record that exists within the file system.
F. The code does not compile.

A

F.
The code does not compile, as Files.deleteIfExists() declares the checked IOException thatmust be handled or declared. Remember, most Files methods declare IOException, especially theones that modify a file or directory. For this reason, option F is correct. If the method was corrected todeclare the appropriate exceptions, then option C would be correct. Option B would also be correct, ifthe method were provided a symbolic link that pointed to an empty directory. Options A and E wouldnot print anything, as Files.isDirectory() returns false for both. Finally, option D would throw aDirectoryNotEmptyException at runtime.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the result of executing the following code? (Choose all that apply.)

 4: var p = Paths.get("sloth.schedule");
 5: var a = Files.readAttributes(p, BasicFileAttributes.class);
 6: Files.mkdir(p.resolve(".backup"));
 7: if(a.size()>0 && a.isDirectory()) {
 8: a.setTimes(null,null,null);
 9: }

A. It compiles and runs without issue.
B. The code will not compile because of line 5.
C. The code will not compile because of line 6.
D. The code will not compile because of line 7.
E. The code will not compile because of line 8.
F. None of the above

A

C, E. The method to create a directory in the Files class is createDirectory(), not mkdir(). Forthis reason, line 6 does not compile, and option C is correct. In addition, the setTimes() method isavailable only on BasicFileAttributeView, not the read-only BasicFileAttributes, so line 8 willalso not compile, making option E correct.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

If the current working directory is /user/home, then what is the output of the following code?

 var p = Paths.get("/zoo/animals/bear/koala/food.txt");     System.out.print(p.subpath(1,3).getName(1).toAbsolutePath());
A. bear
B. animals
C. /user/home/bear
D. /user/home/animals
E. /user/home/food.txt
F. The code does not compile.
G. The code compiles but throws an exception at runtime.
A

C. First, the code compiles and runs without issue, so options F and G are incorrect. Let’s take this onestep at a time. First, the subpath() method is applied to the absolute path, which returns the relativepath animals/bear. Next, the getName() method is applied to the relative path, and since this isindexed from zero, it returns the relative path bear. Finally, the toAbsolutePath() method is appliedto the relative path bear, resulting in the current directory /user/home being incorporated into thepath. The final output is the absolute path /user/home/bear, making option C correct.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Assume /kang exists as a symbolic link to the directory /mammal/kangaroo within the file system.Which of the following statements are correct about this code snippet? (Choose all that apply.)

 var path = Paths.get("/kang");
 if(Files.isDirectory(path) && Files.isSymbolicLink(path))
    Files.createDirectory(path.resolve("joey"));

A. A new directory will always be created.
B. A new directory may be created.
C. If the code creates a directory, it will be reachable at /kang/joey.
D. If the code creates a directory, it will be reachable at /mammal/joey.
E. The code does not compile.
F. The code will compile but always throws an exception at runtime.

A

B, C. The code snippet will attempt to create a directory if the target of the symbolic link exists and isa directory. If the directory already exists, though, it will throw an exception. For this reason, option Ais incorrect, and option B is correct. It will be created in /mammal/kangaroo/joey, and also reachableat /kang/joey because of the symbolic link, making option C correct.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Assume that the directory /animals exists and is empty. What is the result of executing the followingcode? Path path = Path.of(“/animals”); try (var z = Files.walk(path)) { boolean b = z .filter((p,a) -> a.isDirectory() && !path.equals(p)) // x .findFirst().isPresent(); // y System.out.print(b ? “No Sub”: “Has Sub”); }A. It prints No Sub.B. It prints Has Sub.C. The code will not compile because of line x.D. The code will not compile because of line y.E. The output cannot be determined.F. It produces an infinite loop at runtime.

A

C. The filter() operation applied to a Stream takes only one parameter, not two, so the codedoes not compile, and option C is correct. If the code was rewritten to use the Files.find() methodwith the BiPredicate as input (along with a maxDepth value), then the output would be option B, HasSub, since the directory is given to be empty. For fun, we reversed the expected output of the ternaryoperation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

If the current working directory is /zoo and the path /zoo/turkey does not exist, then what is the result of executing the following code? (Choose all that apply.)

 Path path = Paths.get("turkey");
 if(Files.isSameFile(path,Paths.get("/zoo/turkey"))) // z1
    Files.createDirectories(path.resolve("info"));     // z2

A. The code compiles and runs without issue, but it does not create any directories.
B. The directory /zoo/turkey is created.
C. The directory /zoo/turkey/info is created.
D. The code will not compile because of line z1.
E. The code will not compile because of line z2.
F. It compiles but throws an exception at runtime.

A

F. The code compiles without issue, so options D and E are incorrect. The methodFiles.isSameFile() first checks to see whether the Path values are the same in terms of equals().Since the first path is relative and the second path is absolute, this comparison will return false,forcing isSameFile() to check for the existence of both paths in the file system. Since we know/zoo/turkey does not exist, a NoSuchFileException is thrown, and option F is the correct answer.Options A, B, and C are incorrect since an exception is thrown at runtime.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Which of the following correctly create Path instances? (Choose all that apply.)

A. new Path(“jaguar.txt”)
B. FileSystems.getDefault() .getPath(“puma.txt”)
C. Path.get(“cats”,”lynx.txt”)
D. new java.io.File(“tiger.txt”).toPath()
E. new FileSystem().getPath(“lion”)
F. Paths.getPath(“ocelot.txt”)
G. Path.of(Path.of(“.”).toUri())

A

B, D, G. Options A and E are incorrect because Path and FileSystem, respectively, are abstract typesthat should be instantiated using a factory method. Option C is incorrect because the static methodin the Path interface is of(), not get(). Option F is incorrect because the static method in thePaths class is get(), not getPath(). Options B and D are correct ways to obtain a Path instance.Option G is also correct, as there is an overloaded static method in Path that takes a URI instead of aString.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the output of the following code?

     var path1 = Path.of("/pets/../cat.txt");
     var path2 = Paths.get("./dog.txt");
     System.out.println(path1.resolve(path2));
     System.out.println(path2.resolve(path1));

A. /cats.txt/dog.txt
B. /cats.txt/dog.txt/cat.txt
C. /pets/../cat.txt/./dog.txt/pets/../cat.txt
D. /pets/../cat.txt/./dog.txt./dog.txt/pets/../cat.txt
E. None of the above

A

C. The code compiles and runs without issue, so option E is incorrect. For this question, you have toremember two things. First, the resolve() method does not normalize any path symbols, so optionsA and B are not correct. Second, calling resolve() with an absolute path as a parameter returns theabsolute path, so option C is correct, and option D is incorrect.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are some advantages of using Files.lines() over Files.readAllLines()? (Choose all that apply.)

A. It is often faster.
B. It can be run with little memory available.
C. It can be chained with functional programming methods like filter() and map() directly.
D. It does not modify the contents of the file.
E. It ensures the file is not read-locked by the file system.
F. There are no differences, because one method is a pointer to the other.

A

B, C. The methods are not the same, because Files.lines() returns a Stream < String > andFiles.readAllLines() returns a List < String >, so option F is incorrect. Option A is incorrect,because performance is not often the reason to prefer one to the other. Files.lines() processes eachline via lazy evaluation, while Files.readAllLines() reads the entire file into memory all at once.For this reason, Files.lines() works better on large files with limited memory available, and option B is correct. Although a List can be converted to a stream, this requires an extra step; therefore,option C is correct since the resulting object can be chained directly to a stream. Finally, options Dand E are incorrect because they are true for both methods.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Assume monkey.txt is a file that exists in the current working directory. Which statements about the following code snippet are correct? (Choose all that apply.)

 Files.move(Path.of("monkey.txt"), Paths.get("/animals"),
    StandardCopyOption.ATOMIC_MOVE,
    LinkOption.NOFOLLOW_LINKS);

A. If /animals/monkey.txt exists, then it will be overwritten at runtime.
B. If /animals exists as an empty directory, then /animals/monkey.txt will be the new location ofthe file.
C. If monkey.txt is a symbolic link, then the file it points to will be moved at runtime.
D. If the move is successful and another process is monitoring the file system, then it will not see anincomplete file at runtime.
E. The code will always throw an exception at runtime.
F. None of the above

A

D. The target path of the file after the move() operation is /animals, not /animals/monkey.txt, so options A and B are both incorrect. Option B will actually throw an exception at runtime since/animals already exists and is a directory. Next, the NOFOLLOW_LINKS option means that if the sourceis a symbolic link, the link itself and not the target will be copied at runtime, so option C is also incorrect. The option ATOMIC_MOVE means that any process monitoring the file system will not see anincomplete file during the move, so option D is correct. Option E is incorrect, since there arecircumstances in which the operation would be allowed. In particular, if /animals did not exist thenthe operation would complete successfully.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are some advantages of NIO.2 over the legacy java.io.File class for working with files?(Choose three.)

A. NIO.2 supports file system–dependent attributes.
B. NIO.2 includes a method to list the contents of a directory.
C. NIO.2 includes a method to traverse a directory tree.
D. NIO.2 includes a method to delete an entire directory tree.
E. NIO.2 includes methods that are aware of symbolic links.
F. NIO.2 supports sending emails

A

A, C, E. Options A, C, and E are all properties of NIO.2 and are good reasons to use it over thejava.io.File class. Option B is incorrect, as both java.io.File and NIO.2 include a method to listthe contents of a directory. Option D is also incorrect as both APIs can delete only empty directories,not a directory tree. Finally, option F is incorrect, as sending email messages is not a feature of eitherAPI.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

For the copy() method shown here, assume that the source exists as a regular file and that the targetdoes not. What is the result of the following code?

     var p1 = Path.of(".","/","goat.txt").normalize(); // k1
     var p2 = Path.of("mule.png");     Files.copy(p1, p2,
 StandardCopyOption.COPY_ATTRIBUTES); //k2
     System.out.println(Files.isSameFile(p1, p2));

A. It will output false.
B. It will output true.
C. It does not compile because of line k1.
D. It does not compile because of line k2.
E. None of the above

A

A. The code compiles and runs without issue, so options C, D, and E are incorrect. Even though thefile is copied with attributes preserved, the file is considered a separate file, so the output is false,making option A correct and option B incorrect. Remember, isSameFile() returns true only if thefiles pointed to in the file system are the same, without regard to the file contents.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Assume /monkeys exists as a directory containing multiple files, symbolic links, and subdirectories.Which statement about the following code is correct?

 var f = Path.of("/monkeys");
 try (var m =
        Files.find(f, 0, (p,a) -> a.isSymbolicLink())) { // y1
    m.map(s -> s.toString())
       .collect(Collectors.toList())
       .stream()
       .filter(s -> s.toString().endsWith(".txt")) // y2
       .forEach(System.out::println);
 }

A. It will print all symbolic links in the directory tree ending in .txt.
B. It will print the target of all symbolic links in the directory ending in .txt.
C. It will print nothing.
D. It does not compile because of line y1.
E. It does not compile because of line y2.
F. It compiles but throws an exception at runtime.

A

C. The code compiles and runs without issue, so options D, E, and F are incorrect. The most importantthing to notice is that the depth parameter specified as the second argument to find() is 0, meaningthe only record that will be searched is the top-level directory. Since we know that the top directory isa directory and not a symbolic link, no other paths will be visited, and nothing will be printed. Forthese reasons, option C is the correct answer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Which NIO.2 method is most similar to the legacy java.io.File method listFiles?

A. Path.listFiles()
B. Files.dir()
C. Files.ls()
D. Files.files()
E. Files.list()
F. Files.walk()
A

E. The java.io.File method listFiles() retrieves the members of the current directory withouttraversing any subdirectories. Option E is correct, as Files.list() returns a Stream < Path > of asingle directory. Files.walk() is close, but it iterates over the entire directory tree, not just a singledirectory. The rest of the methods do not exist.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are some advantages of using NIO.2’s Files.readAttributes() method rather than readingattributes individually from a file? (Choose all that apply.)

A. It can be used on both files and directories.
B. For reading a single attribute, it is often more performant.
C. It allows you to read symbolic links.
D. It makes fewer round-trips to the file system.
E. It can be used to access file system–dependent attributes.
F. For reading multiple attributes, it is often more performant.

A

D, E, F. Whether a path is a symbolic link, file, or directory is not relevant, so options A and C areincorrect. Using a view to read multiple attributes leads to fewer round-trips between the process andthe file system and better performance, so options D and F are correct. For reading single attributes,there is little or no expected gain, so option B is incorrect. Finally, views can be used to access filesystem–specific attributes that are not available in Files methods; therefore, option E is correct.

17
Q

Assuming the /fox/food-schedule.csv file exists with the specified contents, what is the expectedoutput of calling printData() on it?

/fox/food-schedule.csv
     6am,Breakfast
     9am,SecondBreakfast
     12pm,Lunch
     6pm,Dinner
 void printData(Path path) throws IOException {
    Files.readAllLines(path) // r1
       .flatMap(p -> Stream.of(p.split(","))) // r2
       .map(q -> q.toUpperCase())  // r3
       .forEach(System.out::println);
 }

A. The code will not compile because of line r1.
B. The code will not compile because of line r2.
C. The code will not compile because of line r3.
D. It throws an exception at runtime.
E. It does not print anything at runtime.
F. None of the above

A

B. The readAllLines() method returns a List, not a Stream. Therefore, the call to flatMap() isinvalid, and option B is correct. If the Files.lines() method were instead used, it would print thecontents of the file one capitalized word at a time, with commas removed.

18
Q

What are some possible results of executing the following code? (Choose all that apply.)

 var x = Path.of("/animals/fluffy/..");     Files.walk(x.toRealPath().getParent()) // u1
    .map(p -> p.toAbsolutePath().toString()) // u2
    .filter(s -> s.endsWith(".java")) // u3
    .collect(Collectors.toList())
    .forEach(System.out::println);

A. It prints some files in the root directory.
B. It prints all files in the root directory.
C. FileSystemLoopException is thrown at runtime.
D. Another exception is thrown at runtime.
E. The code will not compile because of line u1.
F. The code will not compile because of line u2.

A

A, D. The code compiles without issue, so options E and F are incorrect. The toRealPath() methodwill simplify the path to /animals and throw an exception if it does not exist, making option Dcorrect. If the path does exist, calling getParent() on it returns the root directory. Walking the rootdirectory with the filter expression will print all .java files in the root directory (along with all .javafiles in the directory tree), making option A correct. Option B is incorrect because it will skip files anddirectories that do not end in the .java extension. Option C is also incorrect as Files.walk() doesnot follow symbolic links by default. Only if the FOLLOW_LINKS option is provided and a cycle isencountered will the exception be thrown.

19
Q

Assuming the directories and files referenced exist and are not symbolic links, what is the result of executing the following code?

 var p1 = Path.of("/lizard",".")
    .resolve(Path.of("walking.txt"));
 var p2 = new File("/lizard/././actions/../walking.txt")
    .toPath();

 System.out.print(Files.isSameFile(p1,p2));
 System.out.print(" ");
 System.out.print(p1.equals(p2));
 System.out.print(" ");
 System.out.print(p1.normalize().equals(p2.normalize()));
A. true true true
B. false false false
C. false true false
D. true false true
E. true false false
F. The code does not compile.
A

D. The code compiles and runs without issue, so option F is incorrect. If you simplify the redundantpath symbols, then p1 and p2 represent the same path, /lizard/walking.txt. Therefore,isSameFile() returns true. The second output is false, because equals() checks only if the pathvalues are the same, without reducing the path symbols. Finally, the normalized paths are the same,since all extra symbols have been removed, so the last line outputs true. For these reasons, option Dis correct.

20
Q

Assuming the current directory is /seals/harp/food, what is the result of executing the followingcode?

 final Path path = Paths.get(".").normalize();
 int count = 0;
 for(int i=0; i
A

B. The normalize() method does not convert a relative path into an absolute path; therefore, the pathvalue after the first line is just the current directory symbol. The for() loop iterates the name values,but since there is only one entry, the loop terminates after a single iteration. Therefore, option B iscorrect.

21
Q

Assume the source instance passed to the following method represents a file that exists. Also, assume/flip/sounds.txt exists as a file prior to executing this method. When this method is executed,which statement correctly copies the file to the path specified by /flip/sounds.txt?

     void copyIntoFlipDirectory(Path source) throws IOException {
        var dolphinDir = Path.of("/flip");
        dolphinDir = Files.createDirectories(dolphinDir);
        var n = Paths.get("sounds.txt");
        \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_;
     }

A. Files.copy(source, dolphinDir)
B. Files.copy(source, dolphinDir.resolve(n), StandardCopyOption.REPLACE_EXISTING)
C. Files.copy(source, dolphinDir, StandardCopyOption.REPLACE_EXISTING)
D. Files.copy(source, dolphinDir.resolve(n))
E. The method does not compile, regardless of what is placed in the blank.
F. The method compiles but throws an exception at runtime, regardless of what is placed in theblank.

A

B. The method compiles without issue, so option E is incorrect. Option F is also incorrect. Eventhough /flip exists, createDirectories() does not throw an exception if the path already exists. IfcreateDirectory() were used instead, then option F would be correct. Next, the copy() commandtakes a target that is the path to the new file location, not the directory to be copied into. Therefore, thetarget path should be /flip/sounds.txt, not /flip. For this reason, options A and C are incorrect.
Since the question says the file already exists, the REPLACE_EXISTING option must be specified or anexception will be thrown at runtime, making option B the correct answer.

22
Q

Assuming the path referenced by m exists as a file, which statements about the following method are correct? (Choose all that apply.)

 void duplicateFile(Path m, Path x) throws Exception {        var r = Files.newBufferedReader(m);
    var w = Files.newBufferedWriter(x,
       StandardOpenOption.APPEND);
    String currentLine = null;
    while ((currentLine = r.readLine()) != null)
       w.write(currentLine);
 }

A. If the path referenced by x does not exist, then it correctly copies the file.
B. If the path referenced by x does not exist, then a new file will be created.
C. If the path referenced x does not exist, then an exception will be thrown at runtime.
D. If the path referenced x exists, then an exception will be thrown at runtime.
E. The method contains a resource leak.F. The method does not compile.

A

B, E. Option F is incorrect, as the code does compile. The method copies the contents of a file, but itremoves all the line breaks. The while() loop would need to include a call to w.newLine() tocorrectly copy the file. For this reason, option A is incorrect. Option B is correct, and options C and Dare incorrect. The APPEND option creates the file if it does not exist; otherwise, it starts writing fromthe end of the file. Option E is correct because the resources created in the method are not closed ordeclared inside a try-with-resources statement.