Programmer II Chapter 8: I/O Flashcards

1
Q

Assume that we have an InputStream instance whose next values are LION and markSupported() returns true. What will the following code output?

public void readData(InputStream is) throws IOException {
System.out.print((char) is.read());
if (is.markSupported()) {is.mark(100);
System.out.print((char) is.read());
System.out.print((char) is.read());
is.reset(); // Resets stream to position before I
}
System.out.print((char) is.read());
System.out.print((char) is.read());
System.out.print((char) is.read());
}

A

LIOION

The code snippet will output LIOION if mark() is supported, and LION otherwise. It’s a good practice to organize your read() operations so that the stream ends up at the same position regardless of whether mark() is supported.

What about the value of 100 we passed to the mark() method? This value is called the readLimit. Itinstructs the stream that we expect to call reset() after at most 100 bytes. If our program calls reset()after reading more than 100 bytes from calling mark(100), then it may throw an exception, depending onthe stream class.

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

Which class would be best to use to read a binary file into a Java object?

A. ObjectWriter
B. ObjectOutputStream
C. BufferedStream
D. ObjectReader
E. FileReader
F. ObjectInputStream
G. None of the above
A
F. 
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. ObjectWriter,BufferedStream, and ObjectReader are not I/O stream classes. ObjectOutputStream is an I/O classbut is used to serialize data, not deserialize it. FileReader can be used to read text file data andconstruct an object, but the question asks what would be the best class to use for binary data.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Which of the following are methods available on instances of the java.io.File class? (Choose all that apply.)

A. mv()
B. createDirectory()
C. mkdirs()
D. move()
E. renameTo()
F. copy()G. mkdir()
A

C, E, G.
The command to move a file or directory using a File is renameTo(), not mv() or move(),making options A and D incorrect, and option E correct. The commands to create a directory using a File are mkdir() and mkdirs(), not createDirectory(), making option B incorrect, and options Cand G correct. The mkdirs() differs from mkdir() by creating any missing directories along the path.Finally, option F is incorrect as there is no command to copy a file in the File class. You would needto use an I/O stream to copy the file along with its contents.

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

What is the value of name after the instance of Eagle created in the main() method is 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. Matt
C. Olivia
D. Bridget
E. null
F. The code does not compile.
G. The code compiles but throws an exception at runtime.
A

B.
The code compiles and runs without issue, so options F and G are incorrect. The key here is thatwhile Eagle is serializable, its parent class, Bird, is not. Therefore, none of the members of Bird willbe serialized. Even if you didn’t know that, you should know what happens on deserialization. Duringdeserialization, Java calls the constructor of the first nonserializable parent. In this case, the Birdconstructor is called, with name being set to Matt, making option B correct. Note that none of theconstructors or instance initializers in Eagle is executed as part of deserialization.

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

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. FileInputStream
C. BufferedWriter
D. ObjectInputStream
E. ObjectOutputStream
F. BufferedReader
G. None of the above, as the first line does not compile.
A

A, D.
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 referencetype of wrapper is InputStream, so we need a class that inherits InputStream. We can eliminateBufferedWriter, ObjectOutputStream, and BufferedReader since their names do not end inInputStream. Next, we see the class must take another stream as input, so we need to choose theremaining streams that are high-level streams. BufferedInputStream is a high-level stream, so optionA is correct. Even though the instance is already a BufferedInputStream, there’s no rule that it can’tbe wrapped multiple times by a high-level stream. Option B is incorrect, as FileInputStream
operates on a file, not another stream. Finally, option D is correct—an ObjectInputStream is a high-level stream that operates on other streams.

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

Which of the following are true? (Choose all that apply.)

A. System.console() will throw an IOException if a Console is not available.
B. System.console() will return null if a Console is not available.
C. A new Console object is created every time System.console() is called.
D. Console can be used only for writing output, not reading input.
E. Console includes a format() method to write data to the console’s output stream.
F. Console includes a println() method to write data to the console’s output stream.

A
B, E. 
The JVM creates one instance of the Console object as a singleton, making option C incorrect.If the console is unavailable, System.console() will return null, making option B correct. Themethod cannot throw an IOException because it is not declared as a checked exception. Therefore,option A is incorrect. Option D is incorrect, as a Console can be used for both reading and writingdata. The Console class includes a format() method to write data to the output stream, making option E correct. Since there is no println() method, as writer() must be called first, option F is incorrect.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Which statements about closing I/O streams are correct? (Choose all that apply.)

A. InputStream and Reader instances are the only I/O streams that should be closed after use.
B. OutputStream and Writer instances are the only I/O streams that should be closed after use.
C. InputStream/ OutputStream and Reader/ Writer all should be closed after use.
D. A traditional try statement can be used to close an I/O stream.
E. A try-with-resources can be used to close an I/O stream.
F. None of the above.

A

C, D, E.
All I/O streams should be closed after use or a resource leak might ensue, making option C correct. While a try-with-resources statement is the preferred way to close an I/O stream, it can beclosed with a traditional try statement that uses a finally block. For this reason, both options D and E are correct.

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

Assume that in is a valid stream whose next bytes are XYZABC. What is the result of calling thefollowing method on the stream, using a count value of 3?

      public static String pullBytes(InputStream in, int count)
            throws IOException {
         in.mark(count);
         var sb = new StringBuilder();
     for(int i=0; i
A

G.
Not all I/O streams support the mark() operation; therefore, without calling markSupported() onthe stream, the result is unknown until runtime. If the stream does support the mark() operation, thenthe result would be XYZY, and option D would be correct. The reset() operation puts the stream backin the position before the mark() was called, and skip(1) will skip X. If the stream does not supportthe mark() operation, a runtime exception would likely be thrown, and option F would be correct.Since you don’t know if the input stream supports the mark() operation, option G is the only correctchoice.

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

Which of the following are true statements about serialization in Java? (Choose all that apply.)

A. Deserialization involves converting data into Java objects.
B. Serialization involves converting data into Java objects.
C. All nonthread classes should be marked Serializable.
D. The Serializable interface requires implementing serialize() and deserialize() methods.
E. Serializable is a functional interface.
F. The readObject() method of ObjectInputStream may throw a ClassNotFoundException even if the return object is not cast to a specific type.

A
A, F. 
In Java, serialization is the process of turning an object to a stream, while deserialization is theprocess of turning that stream back into an object. For this reason, option A is correct, and option B isincorrect. Option C is incorrect, because many nonthread classes are not marked Serializable forvarious reasons. The Serializable interface is a marker interface that does not contain any abstractmethods, making options D and E incorrect. Finally, option F is correct, because readObject()declares the ClassNotFoundException even if the class is not cast to a specific type.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Assuming / 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() throws an exception if /home does not exist

A

A.
Paths that begin with the root directory are absolute paths, so option A is correct, and option C isincorrect. 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 tocreate a File reference to files and directories that do not exist. Option E is also incorrect. Thedelete() method returns false if the file or directory cannot be deleted.

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

What are the requirements for a class that you want to serialize to a stream? (Choose all that apply.)

A. The class must be marked final.
B. The class must extend the Serializable class.
C. The class must declare a static serialVersionUID variable.
D. All static members of the class must be marked transient.
E. The class must implement the Serializable interface.
F. All instance members of the class must be serializable or marked transient.
A
E, F. 
For a class to be serialized, it must implement the Serializable interface and contain instancemembers that are serializable or marked transient. For these reasons, options E and F are correct.Marking a class final does not impact its ability to be serialized, so option A is incorrect. Option B isincorrect, as Serializable is an interface, not a class. Option C is incorrect. While it is a goodpractice for a serializable class to include a static serialVersionUID variable, it is not required.Finally, option D is incorrect as static members of the class are ignored on serialization already.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Given a directory /storage full of multiple files and directories, what is the result of executing thedeleteTree(“/storage”) method on it?

  public static void deleteTree(File file) {
     if(!file.isFile())                    // f1

        for(File entry: file.listFiles())  // f2
           deleteTree(entry);

     else file.delete();
  }

A. It will delete only the empty directories.
B. It will delete the entire directory tree including the /storage directory itself.
C. It will delete all files within the directory tree.
D. The code will not compile because of line f1.
E. The code will not compile because of line f2.
F. None of the above

A

C.
The code compiles, so options D and E are incorrect. The method looks like it will delete adirectory tree but contains a bug. It never deletes any directories, only files. The result of executingthis program is that it will delete all files within a directory tree, but none of the directories. For thisreason, option C is correct.

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

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

      public static void main(String[] args) {
         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. An ArrayIndexOutOfBoundsException is thrown.
D. A NullPointerException is thrown.
E. None of the above, as the code does not compile

A

E.
The code does not compile, as the Writer methods append() and flush() both throw anIOException that must be handled or declared. Even without those lines of code, the try-with-resources statement itself must be handled or declared, since the close() method throws a checkedIOException exception. For this reason, option E is correct. If the main() method was corrected todeclare IOException, then the code would compile. If the Console was not available, it would throwa NullPointerException on the call to c.writer(); otherwise, it would print whatever the user typed in. For these reasons, options B and D would be correct.

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

Suppose that the absolute path /weather/winter/snow.dat represents a file that exists within the filesystem. Which of the following lines of code creates 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. None of the above
A

B, E.
Option A does not compile, as there is no File constructor that takes three parameters. Option Bis correct and is the proper way to create a File instance with a single String parameter. Option C isincorrect, as there is no constructor that takes a String followed by a File. There is a constructor thattakes a File followed by a String, making option E correct. Option D is incorrect because the firstparameter is missing a slash (/) to indicate it is an absolute path. Since it’s a relative path, it is correctonly when the user’s current directory is the root directory.

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

Which of the following are built-in streams in Java? (Choose all that apply.)

A. System.err
B. System.error
C. System.in
D. System.input
E. System.out
F. System.output
A
A, C, E. 
The System class has three streams: in is for input, err is for error, and out is for output.Therefore, options A, C, and E are correct. The others do not exist.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Which of the following are not java.io classes? (Choose all that apply.)

A. BufferedReader
B. BufferedWriter
C. FileReader
D. FileWriter
E. PrintReader
F. PrintWriter
A

E.
PrintStream and PrintWriter are the only I/O classes that you need to know that don’t have a complementary InputStream or Reader class, so option E is correct.

17
Q

Assuming zoo-data.txt exists and is not empty, what statements about the following method are correct? (Choose all that apply.)

      private void echo() throws IOException {
         var o = new FileWriter("new-zoo.txt");
         try (var f = new FileReader("zoo-data.txt");
              var b = new BufferedReader(f); o) {
        o.write(b.readLine());
     }

     o.write("");
  }

A. When run, the method creates a new file with one line of text in it.
B. When run, the method creates a new file with two lines of text in it.
C. When run, the method creates a new file with the same number of lines as the original file.
D. The method compiles but will produce an exception at runtime.
E. The method does not compile.
F. The method uses byte stream classes.

A

A, D.
The method compiles, so option E is incorrect. The method creates a new-zoo.txt file andcopies the first line from zoo-data.txt into it, making option A correct. The try-with-resourcesstatement closes all of declared resources including the FileWriter o. For this reason, the Writer isclosed when the last o.write() is called, resulting in an IOException at runtime and making optionD correct. Option F is incorrect because this implementation uses the character stream classes, whichinherit from Reader or Writer.

18
Q

Assume reader is a valid stream that supports mark() and whose next characters are PEACOCKS. What is the expected output of the following code snippet?

  var sb = new StringBuilder();

  sb. append((char)reader.read());
  reader. mark(10);

  for(int i=0; i < 2; i++) {
     sb.append((char)reader.read());
     reader.skip(2);
  }

  reader.reset();
  reader.skip(0);
  sb.append((char)reader.read());
  System.out.println(sb.toString());

A. PEAE
B. PEOA
C. PEOE
D. PEOS
E. The code does not compile.
F. The code compiles but throws an exception at runtime.
G. The result cannot be determined with the information given.

A

C.
The code compiles without issue. Since we’re told the Reader supports mark(), the code also runswithout throwing an exception. P is added to the StringBuilder first. Next, the position in the streamis marked before E. The E is added to the StringBuilder, with AC being skipped, then the O is addedto the StringBuilder, with CK being skipped. The stream is then reset() to the position before the E.The call to skip(0) doesn’t do anything since there are no characters to skip, so E is added onto theStringBuilder in the next read() call. The value PEOE is printed, and option C is correct.

19
Q

Suppose that you need to write data that consists of int, double, boolean, and String values to a file that maintains the data types of the original data. You also want the data to be performant on large files. Which three java.io stream classes can be chained together to best achieve this result? (Choose three.)

A. FileWriter
B. FileOutputStream
C. BufferedOutputStream
D. ObjectOutputStream
E. DirectoryOutputStream
F. PrintWriter
G. PrintStream
A

B, C, D.
Since you need to write primitives and String values, the OutputStream classes areappropriate. Therefore, you can eliminate options A and F since they use Writer classes. Next,DirectoryOutputStream is not a java.io class, so option E is incorrect. The data should be writtento the file directly using the FileOutputStream class, buffered with the BufferedOutputStreamclass, and automatically serialized with the ObjectOutputStream class, so options B, C, and D arecorrect. PrintStream is an OutputStream, so it could be used to format the data. Unfortunately, sinceeverything is converted to a String, the underlying data type information would be lost. For this reason, option G is incorrect.

20
Q

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 maybe empty.
F. If we check file2 on line n1 within the file system after five iterations, it will contain exactly 50characters.
G. This method contains a resource leak.

A

C, E, G.
First, the method does compile, so options A and B are incorrect. Methods to read/writebyte[] 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 was called after every write. Finally, option G is correct as the reader stream is never closed.

21
Q

Which values when inserted into the blank independently would allow the code to compile? (Choose all that apply.)

  Console console = System.console();
  String color = console.readLine("Favorite color? ");
  console.\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_("Your favorite color is %s", color);
A. reader().print
B. reader().println
C. format
D. writer().print
E. writer().println
F. None of the above
A

C.
Console includes a format() method that takes a String along with a list of arguments and writesit directly to the output stream, making option C correct. Options A and B are incorrect, as reader()returns a Reader, which does not define any print methods. Options D and E would be correct if theline was just a String. Since neither of those methods take additional arguments, they are incorrect.

22
Q

What are some reasons to use a character stream, such as Reader/ Writer, over a byte stream, such asInputStream/ OutputStream? (Choose all that apply.)

A. More convenient code syntax when working with String data
B. Improved performance
C. Automatic character encoding
D. Built-in serialization and deserialization
E. Character streams are high-level streams.
F. Multithreading support

A

A, C.
Character stream classes often include built-in convenience methods for working with Stringdata, so option A is correct. They also handle character encoding automatically, so option C is also correct. The rest of the statements are irrelevant or incorrect and are not properties of all characterstreams.

23
Q

Which of the following fields will be null after an instance of the class created on line 15 is serialized and then deserialized using ObjectOutputStream and ObjectInputStream? (Choose all that apply.)

  1: import java.io.Serializable;
  2: import java.util.List;
  3: public class Zebra implements Serializable {
  4: private transient String name = "George";
  5: private static String birthPlace = "Africa";
  6: private transient Integer age;
  7: List friends = new java.util.ArrayList<>();
  8: private Object stripes = new Object();
  9: { age = 10;}
  10: public Zebra() {
  11: this.name = "Sophia";
  12: }
  13: static Zebra writeAndRead(Zebra z) {
  14: // Implementation omitted
  15: }
  16: public static void main(String[] args) {
  17: var zebra = new Zebra();
  18: zebra = writeAndRead(zebra);
  19: } }
A. name
B. stripes
C. age
D. friends
E. birthPlace
F. The code does not compile.
G. The code compiles but throws an exception at runtime.
A
G. 
The code compiles, so option F is incorrect. To be serializable, a class must implement theSerializable interface, which Zebra does. It must also contain instance members that either aremarked transient or are serializable. The instance member stripes is of type Object, which is notserializable. If Object implemented Serializable, then all objects would be serializable by default,defeating the purpose of having the Serializable interface. Therefore, the Zebra class is notserializable, with the program throwing an exception at runtime if serialized and making option Gcorrect. If stripes were removed from the class, then options A and C would be the correct answers,as name and age are both marked transient.