Chapter 14 I/O Flashcards
Review Questions
1. Which class would be best to use to read a binary file into a Java object?
A. BufferedStream
B. FileReader
C. ObjectInputStream
D. ObjectReader
E. ObjectOutputStream
F. ObjectWriter
G. None of the above
C.
- Since the question asks about putting data into a structured object, the best class would be one that deserializes the data. Therefore,
ObjectInputStream
is the best choice, which is option C. - ObjectWriter, BufferedStream, and ObjectReader are not I/O stream classes.
- ObjectOutputStream is an I/O class but is used to serialize data, not deserialize it.
- FileReader can be used to read text file data and construct an object, but the question asks what would be the best class to use for binary data.
2. Assuming that /
is the root directory within the file system, which of the following are true statements? (Choose all that apply.)
A. /home/parrot
is an absolute path.
B. /home/parrot
is a directory.
C. /home/parrot
is a relative path.
D. new File("/home")
will throw an exception if /home
does not exist.
E. new File("/home").delete()
will throw an exception if /home
does not exist.
F. A Reader offers character encoding, making it more useful when working with String data than an InputStream.
G. A Reader offers multithreading support, making it more useful than an InputStream.
A, F.
- Paths that begin with the root directory are absolute paths, so option A is correct,
- and option C is incorrect. Option B is incorrect because the path could be a file or directory within the file system. There is no rule that files have to end with a file extension.
- Option D is incorrect, as it is possible to create a File reference to files and directories that do not exist.
- Option E is also incorrect. The delete() method returns false if the file or directory cannot be deleted.
- Character stream classes often include built-in convenience methods for working with String data, so option F is correct.
- There is no such optimization for multi-threading, making option G incorrect.
3. What are possible results of executing the following code? (Choose all that apply.)
public static void main(String[] args) throws IOException { String line; var c = System.console(); Writer w = c.writer(); try (w) { if ((line = c.readLine("Enter your name: ")) != null) w.append(line); w.flush(); } }
A. The code runs, but nothing is printed.
B. The code prints what was entered by the user.
C. The code behaves the same if throws IOException is removed.
D. A NullPointerException may be thrown.
E. A NullPointerException will always be thrown.
F. A NullPointerException will never be thrown.
G. The code does not compile.
B, D.
- If the console is unavailable, System.console() will return null, making option D correct
- and options E and F incorrect.
- The writer methods throw a checked IOException, making option C incorrect.
- The code works correctly, prompting for input and printing it. Therefore, option A is incorrect
- and option B is correct.
4. 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.
F.
-
The code does not compile, as
Files.deleteIfExists()
declares the checked IOException that must be handled or declared. - Remember, most Files methods declare IOException, especially the ones that modify a file or directory. For this reason, option F is correct.
- If the method were corrected to declare the appropriate exceptions, option C would be correct.
- Option B would also be correct if the method were provided a symbolic link that pointed to an empty directory.
- Options A and E would not print anything, as Files.isDirectory() returns false for both.
- Finally, option D would throw a DirectoryNotEmptyException at runtime.
5. Assume that the directory /animals exists and is empty. What is the result of executing the following code?
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.
C.
- The
filter()
operation applied to a Stream<Path>
takes only one parameter, not two, so the code does not compile, and option C is correct. - If the code were rewritten to use the Files.find() method with the BiPredicate as input (along with a maxDepth value), the output would be option B, Has Sub, since the directory is given to be empty.
- For fun, we reversed the expected output of the ternary operation.
6. What would be the value of name if the instance of Eagle created in the main() method were serialized and then deserialized?
import java.io.Serializable; class Bird { protected transient String name; public void setName(String name) { this.name = name; } public String getName() { return name; } public Bird() { this.name = "Matt"; } } public class Eagle extends Bird implements Serializable { { this.name = "Olivia"; } public Eagle() { this.name = "Bridget"; } public static void main(String[] args) { var e = new Eagle(); e.name = "Adeline"; } }
A. Adeline
B. Bridget
C. Matt
D. Olivia
E. null
F. The code does not compile.
G. The code compiles but throws an exception at runtime.
C.
- The code compiles and runs without issue, so options F and G are incorrect.
- The key here is that while Eagle is serializable, its parent class, Bird, is not. Therefore, none of the members of Bird will be serialized.
- Even if you didn’t know that, you should know what happens on deserialization.
- During deserialization, Java calls the constructor of the first non-serializable parent.
- In this case, the Bird constructor is called, with name being set to Matt, making option C correct.
- Note that none of the constructors or instance initializers in Eagle are executed as part of deserialization.
7. Assume that /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 will always throw an exception at runtime.
B, C.
- The code snippet will attempt to create a directory if the target of the symbolic link exists and is a directory.
- If the directory already exists, though, it will throw an exception. For this reason, option A is incorrect,
- and option B is correct. It will be created in /mammal/kangaroo/joey
- and also reachable at /kang/joey because of the symbolic link, making option C correct.
8. Assuming that the /fox/food-schedule.csv file exists with the specified contents, what is the expected output 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
B.
- The readAllLines() method returns a List, not a Stream. Therefore, the call to flatMap() is invalid, and option B is correct.
- If the Files.lines() method were used instead, it would print the contents of the file one capitalized word at a time with the commas removed.
9. Given the following method, which statements are correct? (Choose all that apply.)
public void copyFile(File file1, File file2) throws Exception { var reader = new InputStreamReader(new FileInputStream(file1)); try (var writer = new FileWriter(file2)) { char[] buffer = new char[10]; while(reader.read(buffer) != -1) { writer.write(buffer); // n1 }}}
A. The code does not compile because reader is not a buffered stream.
B. The code does not compile because writer is not a buffered stream.
C. The code compiles and correctly copies the data between some files.
D. The code compiles and correctly copies the data between all files.
E. If we check file2 on line n1 within the file system after five iterations of the while loop, it may be empty.
F. If we check file2 on line n1 within the file system after five iterations, it will contain exactly 50 characters.
G. This method contains a resource leak.
C, E, G.
- First, the method does compile, so options A and B are incorrect.
- Methods to read/write byte[] values exist in the abstract parent of all I/O stream classes.
- This implementation is not correct, though, as the return value of read(buffer) is not used properly.
- It will only correctly copy files whose character count is a multiple of 10, making option C correct and option D incorrect.
- Option E is also correct as the data may not have made it to disk yet.
- Option F would be correct if the flush() method were called after every write.
- Finally, option G is correct as the reader stream is never closed.
10. 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())
B, D, G.
- Options A and E are incorrect because Path and FileSystem, respectively, are abstract types that should be instantiated using a factory method.
- Option C is incorrect because the static method in the Path interface is of(), not get().
- Option F is incorrect because the static method in the Paths 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 a String.
11. Which classes will allow the following to compile? (Choose all that apply.)
var is = new BufferedInputStream(new FileInputStream("z.txt")); InputStream wrapper = new \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ (is); try (wrapper) {}
A. BufferedInputStream
B. BufferedReader
C. BufferedWriter
D. FileInputStream
E. ObjectInputStream
F. ObjectOutputStream
G. None of the above, as the first line does not compile
A, E.
- The code will compile if the correct classes are used, so option G is incorrect.
- Remember, a try-with-resources statement can use resources declared before the start of the statement.
- The reference type of wrapper is InputStream, so we need a class that inherits InputStream. We can eliminate BufferedWriter, ObjectOutputStream, and BufferedReader since their names do not end in InputStream.
- Next, we see the class must take another stream as input, so we need to choose the remaining streams that are high-level streams.
- BufferedInputStream is a high-level stream, so option A is correct. Even though the instance is already a BufferedInputStream, there’s no rule that it can’t be wrapped multiple times by a high-level stream.
- Option D is incorrect, as FileInputStream operates on a file, not another stream. Finally, option
- E is correct—an ObjectInputStream is a high-level stream that operates on other streams.
12. 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
C, E.
- The method to create a directory in the Files class is createDirectory(), not mkdir().
- For this reason, line 6 does not compile, and option C is correct.
- In addition, the setTimes() method is available only on BasicFileAttributeView, not the read-only BasicFileAttributes, so line 8 will also not compile, making option E correct.
13. Which of the following are true statements about serialization in Java? (Choose all that apply.)
A. All non-null instance members of the class must be serializable or marked transient.
B. Records are automatically serializable.
C. Serialization involves converting data into Java objects.
D. Serializable is a functional interface.
E. The class must declare a static serialVersionUID variable.
F. The class must extend the Serializable class.
G. The class must implement the Serializable interface.
A, G.
- For a class to be serialized, it must implement the Serializable interface and contain instance members that are serializable or marked transient. For these reasons, options A and G are correct and option F is incorrect.
- Option B is incorrect because even records are required to implement Serializable to be serialized.
- Option C is incorrect because it describes deserialization.
- The Serializable interface is a marker interface that does not contain any abstract methods, making option D incorrect.
- While it is a good practice for a serializable class to include a static serialVersionUID variable, it is not required. Therefore, option E is incorrect as well.
14. What is the output of the following code? (Choose three.)
22: var p1 = Path.of("/zoo/./bear","../food.txt"); 23: p1.normalize().relativize(Path.of("/lion")); 24: System.out.println(p1); 25: 26: var p2 = Paths.get("/zoo/animals/bear/koala/food.txt"); 27: System.out.println(p2.subpath(1,3).getName(1)); 28: 29: var p3 = Path.of("/pets/../cat.txt"); 30: var p4 = Paths.get("./dog.txt"); 31: System.out.println(p4.resolve(p3));
A. ../../lion
B. /zoo/./bear/../food.txt
C. animal
D. bear
E. /pets/../cat.txt
F. /pets/../cat.txt/./dog.txt
B, D, E.
- Path is immutable, so line 23 is ignored. If it were assigned to p1, option A would be correct.
- Since it is not assigned, the original value is still present, which is option B.
- Moving on to the second section, the subpath() method on line 27 is applied to the absolute path, which returns the relative path animals/bear.
- Next, the getName() method is applied to the relative path, and since this is indexed from 0, it returns the relative path bear. Therefore, option D is correct.
- Finally, remember calling resolve() with an absolute path as a parameter returns the absolute path, so option E is correct.
15. Suppose that the working directory is /weather
and the absolute path /weather/winter/snow.dat
represents a file that exists within the file system. Which of the following lines of code create an object that represents the file? (Choose all that apply.)
A. new File("/weather", "winter", "snow.dat")
B. new File("/weather/winter/snow.dat")
C. new File("/weather/winter", new File("snow.dat"))
D. new File("weather", "/winter/snow.dat")
E. new File(new File("/weather/winter"), "snow.dat")
F. Path.of("/weather/winer/snow.dat").toFile();
G. None of the above
B, E, F.
- Option A does not compile, as there is no File constructor that takes three parameters.
- Option B is correct and is the proper way to create a File instance with a single String parameter.
- Option C is incorrect, as there is no constructor that takes a String followed by a File. There is a constructor that takes a File followed by a String, making option E correct.
- Option D is incorrect because the first parameter is missing a slash (/) to indicate it is an absolute path. Since it’s a relative path, it is correct only when the user’s current directory is the root directory.
- Finally, option F is correct as it creates a File from a Path.