Java OCP Part8. I/O and File

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

C. Since neither File(s).exists() nor File(s).mkdir() throw IOException, the class compiles, making Option E incorrect. If /woods/forest exists, then the first branch of the if-then statement executes, printing 'true' at runtime. On the other hand, if /woods/forest does not exist, the program will print true if /woods exists and false if /woods does not exist. Unlike mkdirs(), which if used would always return true in this case, mkdir() will return false if part of the parent path is missing. For this reason, Option C is correct, and Options A and B are incorrect. Finally, Option D is incorrect. This code is not expected to throw an exception at runtime. If the path could not be created, the mkdir() method just returns false.

Which possible outcome is true? (Assume the file system available and able to be modified.) public class CreateTree { public boolean createTree(String tree) { if( new File(tree).exists() ) return true; else return new File(tree).mkdir(); } public static void main(String[] seeds) { final CreateTree creator = new CreateTree(); System.out.print( creator.createTree("/woods/forest") ); } } A. The class compiles and always prints true at runtime. B. The class compiles and always prints false at runtime. C. The class compiles but the output cannot be determined until runtime. D. The class compiles but may throw an exception at runtime. E. The class does not compile.

B,C Because a directory containing files or subdirectories is copied or moved in its entirety. Directories can only be deleted if they are empty. Trying to delete a nonempty directory will throw a DirectoryNotEmptyException. Not that the question says "usually" because copy and move success depends on file permissions.

Which statement are correct (choose all that apply): A. A nonempty directory can usually be deleted using Files.delete B. A nonempty directory can usually be moved using Files.move C. A nonempty directory can usually be copied using Files.copy

A, B, D. Option A is correct because the java.io stream classes implement Closeable and can be used with try-with-resources statements, while java.util.stream.Stream does not implement Closeable. Option B is correct since the Reader/Writer classes are used for handling character data. There are primitive stream classes in java.util.stream, but none for handling character data, such as CharStream. Option C is incorrect because neither requires all data objects to implement Serializable. Option D is correct since flush() is found in Writer and OutputStream but not in any of the java.util.stream classes. Option E is incorrect since both types of streams contain a skip() method in some of their classes. Lastly, Option F is incorrect. There is no sort method found in any of the java.io classes. While there is a sorted() method in java.util.stream.Stream, the question is asking about what features are available in a java.io stream class and not in a java.util.stream.Stream class

Which statements describe a java.io stream class and cannot be applied to a java.util.stream.Stream class? (Choose three.) A. Can be used with try-with-resources statement B. Includes a class or set of classes used solely for working with character data C. Requires all data objects to implement Serializable D. Some classes contain a flush() method. E. Some classes contain a method to skip over data. F. Some classes contain a method to sort the data.

B, D, E. Console defines two output methods, format() and printf(), that are identical in function, so B and D are correct. A, C, and F are each incorrect, because there is no such method with that name defined in the Console class. You can also use the writer() method to gain access to the Console's PrintWriter object, so E is correct.

Which values when inserted into the blank would allow the code to compile? (Choose all that apply.) 1: Console console = System.console(); 2: String color = console.readLine("What is your favorite color? "); 3: console.__________("Your favorite color is "+color); A. print B. printf C. println D. format E. writer().println F. out

D, F

Why shouldn't every class be marked Serializable? (Choose all) A. The compiler will throw an exception if certain classes are marked Serializable. B. Only final classes can be marked Serializable. C. Classes can implement only one interface, so marking them Serializable would prevent them from using any other interface. D. The data of some classes cannot be easily serialized, such as those managing threads or processes. F. Classes that store most of their data in static fields would not be easily serialized.

D. The code compiles and runs without issue, so Options A and B are incorrect. The problem with the implementation is that checking if ios.readObject() is null is not the recommended way of iterating over an entire file. For example, the file could have been written with writeObject(null) in-between two non-null records. In this case,the reading of the file would stop on this null value, before the end of the file has been reached. For this reason, Option D is the correct answer. Note that the valid way to iterate over all elements of a file using ObjectInputStream is to continue to callreadObject() until an EOFException is thrown

class Student implements Serializable {} public static void main(String[] grades) { try(ObjectInputStream ios = new ObjectInputStream( new FileInputStream( new File("C://students.data") ) ) ) { Student record; while( (record = (Student) ios.readObject() ) != null) { System.out.print(record);} } catch (EOFException e) { } catch (Exception e) { throw new RuntimeException(e); } } } // Assume the file exists and contains data. Which is correct? A. The code does not compile. B. The code compiles but prints an exception at runtime. C. The program runs and prints all students in the file. D. The program runs but may only print some students in the files.

D, E. The code does not compile due to a number of issues, so A and F are incorrect. First off, the readObject() method is not available to the InputStream class, and since the ObjectInputStream has been upcast to InputStream, the code will not compile due to line 18, so E is correct. Line 18 will also not compile because the return type of readObject() is of type Object and must be cast explicitly to Bird in order to be assigned to the Bird reference. Furthermore, constructors and methods on lines 16, 17, and 18 throw checked IOExceptions that must be caught, so D is also correct. Note that line 18 also throws ClassNotFoundException. Lines 3 and 5 compile without issue, so B and C are incorrect. It should be noted that even if the compilation problems were resolved, the code would still throw an exception at runtime since the Bird class includes a Tail reference as a member, and the Tail class does not implement Serializable.

2: public class Tail {} 3: public class Bird implements Serializable { 4: private String name; 5: private transient int age; 6: private Tail tail; 15: public void main(String[] args) { 16: try(*InputStream is* = new ObjectInputStream( 17: new BufferedInputStream(new FileInputStream("birds.dat") ) ) ) { 18: Bird bird = *is.readObject()*; 19: } } } // What is the result of executing the following code? (Choose all.) A. It compiles and runs without issue. B. It compiles but throw runtime exception. C. The code will not compile because of line 5. D. The code will not compile because of lines 16-17. E. The code will not compile because of line 18. F. It compiles but throws an exception at runtime.

C, D, F. The System class method is console(), not getConsole(), and the readLine() method returns a String, not a char[].

5. public static void main(String[] args) { 6. Console c = *System.getConsole()*; 7. *char[] u = c.readLine("%s", "username: ")*; 8. System.out.println("hello " + u); 9. char[] pw; 10. if(c != null && (pw = c.readPassword("%s", "password: ")) != null) 11. // check for valid password 13. } // Which are true? (Choose all that apply.) A. Compilation succeeds. B. Compilation fails due to a single error in the code. C. Compilation fails due to multiple errors in the code. D. By default, the readLine() method echoes the user's keystrokes. E. By default, the readPassword() method echoes the user's keystrokes. F. All of the Console class's methods that write to the console's output stream allow you to specify the format of the output stream.

C,D. Option (a) won't compile. Class PrintWriter doesn't define method writeInt(). It defines overloaded write() methods with accepted method parameters of type char[], int, or String. Option (b) is incorrect because it writes all the given XML in a single line, without inserting line breaks. Option (c) is correct. The overloaded println() method in PrintWriter writes data to the underlying stream and then terminates the line. Option (d) is correct. A PrintWriter can be used to write to a byte stream (OutputStream) and a character stream (Writer).

<emp> <id>8743</id> Given this XML, which options, inserted at *L1*, will write XML exactly to a file? public void writeEmpData() throws IOException { File f = new File("empdata.txt"); *L1* pw.flush(); pw.close(); } A. PrintWriter pw = new PrintWriter(f); pw.println("<emp>"); pw.write("<id>"); pw.write*Int*(8743); pw.write("</id>"); B. PrintWriter pw = new PrintWriter(new FileOutputStream(f)); pw.write("<emp>"); pw.write("<id>8743</id>"); C. PrintWriter pw = new PrintWriter(f); pw.println("<emp>"); pw.println("<id>8743</id>"); D. PrintWriter pw = new PrintWriter(new FileOutputStream(f)); pw.println("<emp>"); pw.println("<id>8743</id>");

C. First off, the code compiles without issue. The first method call to mkdirs() creates two directories, /templates and /templates/proofs. The next mkdir() call is unnecessary, since /templates/proofs already exists. That said, calling it on an existing directory is harmless and does not cause an exception to be thrown at runtime. Next, a file draft.doc is created in the /templates directory. The final two lines attempt to remove the newly created directories. The first call to delete() is successful because /templates/proofs is an empty directory. On the other hand, the second call to delete() fails to delete the directory /templates because it is non-empty, containing the file draft.doc. Neither of these calls trigger an exception at runtime, though, with delete() just returning a boolean value indicating whether the call was successful. Therefore, our program ends without throwing any exceptions,and Option C is the correct answer

Assume the directories referenced in the class do not exist prior to the execution of the program and that the file system is available and able to be written. public class Resume { public void resetWorkingDirectory() throws Exception { File f1 = new File("/templates/proofs"); f1.mkdirs(); File f2 = new File("/templates"); f2.mkdir(); // k1 new File(f2,"draft.doc").createNewFile(); f1.delete(); f2.delete(); // k2 } public static void main(String... leads) throws Exception { new Resume().resetWorkingDirectory(); } } // What is the output of the application? A. Line k1 does not compile or triggers an exception at runtime. B. Line k2 does not compile or triggers an exception at runtime. C. The code compiles and runs without printing an exception. D. None of the above

D. The code compiles, so Option C is incorrect. The FileInputStream does not support marks, though, leading to an IOException at runtime when the reset() method is called. For this reason, Option D is the correct answer. Be suspicious of any code samples that call the mark() or reset() method without first calling markSupported().

Assume the file prime6.txt exists and contains the first six prime numbers as bytes: 2 ,3 , 5 , 7 , 11 , 13 . try ( InputStream is = new FileInputStream("prime6.txt") ) { is.skip(1); is.read(); is.skip(1); is.read(); is.mark(4); is.skip(1); is.reset(); System.out.print(is.read()); } // What is the output of the application? A. 11 B. 13 C. The code does not compile. D. The code compiles but throws an exception at runtime.

B. A process attempting to serialize an object will throw a NotSerializableException if the class or one of its contained classes does not properly implement the Serializable interface.

Cat class is marked as Serializable and contains a reference to a Tail object which is not. What would be when attempting to serialize and de-serialize a Cat object? A. reference to Tail object is null. B. NotSerializableException C. Cat object will be exactly as it was before.

С,F F is correct, because most methods in the File class that interact with the file system are capable of throwing an exception at runtime, such as when the directory does not exist

Choose all that apply. 1: public static void deleteTree(File file) { 2: if ( !file.isFile() ) 3: for( File entry: file.listFiles() ) 4: deleteTree(entry); 5: else file.delete(); 6: } A. It can delete a directory that contains only files. B. It can delete a directory tree of arbitrary length. C. It can delete a single file. D. The code will not compile because of line 2. E. The code will not compile because of line 3. F. It compiles but may throw an exception at runtime.

C. Given a valid instance of Console, reader() returns an instance of Reader, while writer() returns an instance of PrintWriter. Reader and PrintWriter was not an answer choice though, making Option C the next best choice since PrintWriter inherits Writer. Options A and B are incorrect because PrintReader is not defined in the java .io library. Option D is incorrect because the type of the instance returned by reader() is Reader, which does not inherit StringReader

Fill in the blanks: Given a valid Console instance, reader() returns a__________ , while writer() returns a __________. A. PrintReader , PrintWriter B. PrintReader , Writer C. Reader , PrintWriter D. StringReader , Writer

16,17,18) A BufferedWriter can be constructed only by wrapping a Writer. Lines 16, 17, and 18 are correct because BufferedWriter, FileWriter, and PrintWriter all extend Writer. (Note: BufferedWriter is just a decorator class which is used extensively in the java.io package to allow you to extend the functionality of other classes.)

Given that bw is a reference to a valid BufferedWriter, which lines correct? 15. BufferedWriter b1 = new BufferedWriter(new File("f") ); 16. BufferedWriter b2 = new BufferedWriter(new FileWriter("f1") ); 17. BufferedWriter b3 = new BufferedWriter(new PrintWriter("f2") ); 18. BufferedWriter b4 = new BufferedWriter(new BufferedWriter(bw) );

D. To answer the question, you need to identify three of the four ways to call the system-independent file name separator. Option A is valid because it is the fully qualified name of the property. Option B is also valid because File.separator and File.separatorChar are equivalent. While accessing a static variable using an instance is discouraged, as shown inOption B, it is allowed. Option C is valid and a common way to read the character using the System class. Finally, Option D is the correct answer and one call that cannot be used to get the system-dependent name separator character. Note that System.getProperty("path.separator") is used to separate sets of paths, not names within a single path

Given the following class, three of the values ensure it runs properly on various different systems. Which value does not? public class Store { private final String directory; public Store(String directory) { this.directory = directory; } public File getDatabaseFolder(String file) { return new File(directory + __________ + file); } } A. java.io.File.separator B. new File(new String()).separatorChar C. System.getProperty("file.separator") D. System.getProperty("path.separator")

D. The first compilation error is that the FileReader constructor call is missing the new keyword. The second compilation error is that the music variable is marked final, but then modified in the while loop. The third compilation problem is that the readMusic() method fails to declare or handle an IOException. Even though the IOException thrown by readLine() is caught, the one thrown by the implicit call to close() via the try-with-resources block is not caught.

How many compilation errors does the following class contain? public void readMusic(File f) { try ( BufferedReader r = new BufferedReader(*FileReader(f)* ) ) { *final String music* = null; try { while( ( music = r.readLine() ) != null ) System.out.println(music); } catch (*IOException* e) {} } catch (*FileNotFoundException* e) { throw new RuntimeException(e); } finally {} } A. None B. One C. Two D. Three

B, E. The method does not call the markSupported() prior to calling mark() and reset(). The input variable could be a subclass of Reader that does not support this functionality. In this situation, the method would ignore the mark() call and throw an IOException on the reset() method, making Option A incorrect and Option B correct. On the other hand, if marking the stream is supported, then no exception would be thrown. First, line 24 skips two values, 1 and 2. On line 25, the mark() method is called with a value of 5, which is the number of characters that can be read and stored before the marked point is invalidated. Next, line 26 would skip another value but is undone by the reset() on line 27. The next value to be read would be the third value, 3. The read(char[]) call would then read up to five values, since that is the size of the array. Since only four are left (4, 5, 6, 7) the method would return a value of 4, corresponding to the number of characters read from the stream. For these reasons, the output is 3-4, making Option E the correct answer. Options C and D can be eliminated because read() returns an int value, not a char.

Let's say we have a Reader instance that will produce the characters with the numeric values {1,2,3,4,5,6,7}. Which of the following are possible outcomes of executing the checkLottoNumbers() method with this Reader instance? (Choose two.) 23: public String checkLottoNumbers(Reader r) throws IOException { 24: r.read(); r.skip(1); 25: r.mark(5); 26: r.skip(1); 27: r.reset(); 28: return r.read()+"-"+r.read(new char[5]); 29: } A. An IOException on line 25 B. An IOException on line 27 C. 'c'-4 is returned. D. 'd'-3 is returned. E. 3-4 is returned. F. 4-3 is returned.

B, C. Option B is correct because Java requires a backslash to be escaped with another backslash. Option C is also correct because Java will convert the slashes to the right one when working with paths.

Suppose that the file c:\book\java exists. Which of the following lines of code creates an object that represents the file? (Choose all that apply.) A. new File("c:\book\java"); B. new File("c:\\book\\java"); C. new File("c:/book/java"); D. new File("c://book//java");

B, C, D. Since you need to write primitives and String values, the OutputStream classes are appropriate. Therefore, you can eliminate A and F since they are not OutputStreamclasses. Next, DirectoryStream is not a java.io class, so E is incorrect. The data should be written to the file directly using the FileOutputStream class, buffered with the BufferedOutputStreamclass and automatically serialized with the ObjectOutputStream class, so B, C, and D are correct. G is incorrect because it is not related.

Suppose that you need to write data that consists of int, double, boolean, and String values to a file that maintains the format of the original data. For performance reasons, you also want to buffer the data. Which three java.io classes can be chained together to best achieve this result? A. FileWriter B. FileOutputStream C. BufferedOutputStream D. ObjectOutputStream E. DirectoryStream F. PrintWriter G. PipedOutputStream

PrintStream (inherits OutputStream) PrintWriter (inherits Writer)

Two high-level stream classes that write formatted representation of Java objects to a text-based output stream?

InputStream (read bytes) OutputStream (write bytes) Reader (read chars) Writer (write chars)

What four abstract classes that are the parents of all stream classes defined within the Java API ?

FileInputStream (Reads file data as bytes) FileOutputStream (Writes file data as bytes) FileReader (Reads file data as characters) FileWriter (Writes file data as characters)

What four low level file-related classes which allow to read/write bytes and string data to/from I/O stream?

E. The readObject() method returns an Object instance, which must be explicitly castto Cruise in the second try-with-resources statement. For this reason, the code doesnot compile, and Option E is the correct answer. If the explicit cast was added, thecode would compile but throw a NotSerializableException at runtime, since Cruisedoes not implement the Serializable interface. If both of these issues were corrected,the code would run and print 4,null. The schedule variable is marked transient, so it defaults to null when deserialized, while numPassengers is assigned the value it hadwhen it was serialized. Note that on deserialization, the constructors and instanceinitializers are not executed.

What is the output of the following application? Assume the file system is available and able to be written to and read from. public class Cruise { private int numPassengers = 1; private transient String schedule = "NONE"; { numPassengers = 2; } public Cruise() { this.numPassengers = 3; this.schedule = "Tropical Island"; } public static void main(String... passengers) throws Exception { try (ObjectOutputStream o = new ObjectOutputStream( new FileOutputStream("ship.txt") ) ) { Cruise c = new Cruise(); c.numPassengers = 4; c.schedule = "Casino"; o.writeObject(c); } try ( ObjectInputStream i = new ObjectInputStream( new FileInputStream("ship.txt") ) ) { Cruise c = i.readObject(); System.out.print(c.numPassengers+c.schedule); } } } A. 2NONE B. 3null C. 4Casino D. 4null E. The class does not compile. F. The class compiles but throws an exception at runtime

B, D. Option B is correct because this is the right way to read data from the Console. Option D is also correct. If there is no console available, a NullPointerException is thrown. The readLine method does not throw an IOException

What is the result of executing the following code? (Choose all that apply.) String line; Console c = System.console(); if ((line = c.readLine()) != null) System.out.println(line); A. The code runs without error but prints nothing. B. The code prints what was entered by the user. C. An ArrayIndexOutOfBoundsException might be thrown. D. A NullPointerException might be thrown. E. An IOException might be thrown. F. The code does not compile.

B,D,E This is correct code for reading a line from the console and writing it back out to the console, making option B correct. Options D and E are also correct. If no console is available, a NullPointerException is thrown. The append() method throws an IOException.

What is the result of executing the following code? (Choose all.) String line; Console c = System.console(); Writer w = c.writer(); if ((line = c.readLine()) != null) w.append(line); w.flush(); A. The code runs without error but prints nothing. B. The code prints what was entered by the user. C. An ArrayIndexOutOfBoundsException might be thrown. D. A NullPointerException might be thrown. E. An IOException might be thrown. F. The code does not compile.

A, C, D. A. FileWriter out = new FileWriter(new File("zoo.log")); C. PrintWriter out = new PrintWriter(new FileWriter("zoo.log")); D. FileReader in = new FileReader(new File("zoo.log"));

Which can be constructed using an instance of java.io.File? (Choose all that apply.) A. java.io.FileWriter B. java.io.BufferedWriter C. java.io.PrintWriter D. java.io.FileReader E. java.io.BufferedReader

A,D Note that a BufferedInputStream can be wrapped twice, since high-level streams can take other high-level streams.

Which classes will allow the following to compile? (Choose all that apply.) InputStream is = new BufferedInputStream(new FileInputStream("zoo.txt")); InputStream wrapper = new ________________ (is); A. BufferedInputStream B. FileInputStream C. BufferedWriter D. ObjectInputStream E. ObjectOutputStream F. BufferedReader

5,7,9 Line 5 is incorrect because String does not implement AutoCloseable. Not all objects can be declared in a try-with-resources try clause. Line 7 is incorrect because RainException is a checked exception and is not declared or handled. Line 9 is incorrect because s is declared in the try clause and is therefore out of scope for the finally block

Which lines contain compilation issues? 1: public class Compiles { 2: class RainException extends Exception {} 4: public static void main(String[] args) { 5: try(Scanner s = new Scanner("rain"); *String line =""*;) { 6: if ( s.nextLine().equals("rain") ) 7: *throw new RainException()*; 8: } finally { 9: *s.*close(); 10: } } }

C,E,G To move a file using java.io.File, you should use the renameTo() method, since there are no move() or mv() methods. Therefore, E is correct, and A and D are incorrect. To create a directory or chain of directories using java.io.File, you should use mkdir()or mkdirs(), respectively, because there is no createDirectory() method. Therefore, C and G are correct, and B is incorrect. Finally, there is no copy() method in the java.io.File class, so F is incorrect. Copying a file with java.io would require reading the contents using a stream.

Which of the following are methods available to instances of the java.io.File class? (Choose all) A. mv() B. createDirectory() C. mkdirs() D. move() E. renameTo() F. copy() G. mkdir()

A,E

Which of the following are true statements about serialization in Java? (Choose all that apply.) A. The process of converting serialized data back into memory is called deserialization. B. All non-thread classes should be marked Serializable. C. The Serializable interface requires implementing serialize() and deserialize() methods. D. The Serializable interface is marked final and cannot be extended. E. The readObject() method of ObjectInputStream may throw a ClassNotFoundException even if the return object is not explicitly cast.

D, F. To begin with, the read() method of both classes returns an int value, making Option A incorrect. As you may recall from your studies, neither use byte or char, so that -1 can be returned when the end of the stream is reached without using an existing byte or char value. Option B is incorrect because neither contain a flush()method, while Option C is incorrect because they both contain a skip() method. Both InputStream and Reader are abstract classes, not interfaces, making Option D correct and Option E incorrect. That leaves Option F as a correct answer. Both can be used to read character or String data, although Reader is strongly recommended, given its built-in support for character encodings.

Which of the following statements about InputStream and Reader are correct? A. One contains a read() method that returns a byte value, while the other contains a read() method that returns an int value. B. Only one of them contains a flush() method. C. Only one of them contains a skip() method. D. They are both abstract classes. E. They are both interfaces. F. They can both be used to read character data.

D. You may have mutliple copies of the same object in the stream and when you read the stream back, you will get multiple objects. C incorrect because the no-argument constructor of the first non-serializable super class ONLY is invoked. This constructor may internally invoke any constructor of its super class.

Which of the following statements about Java serialization are correct? A. For a class to be serializable, that class and each of its super classes must implement Serializable interface. B. When deserializing an object, the no-argument constructor of the class and each of its super classes is invoked. C. When deserializing an object, the no-argument constructor each of its super classes that does not implement Serializable interface is invoked. D. Multiple copies of an object may be added to a stream.

A, B, D, G. ObjectOutputStream and ObjectInputStream perform serialization and deserialization on a low-level stream, respectively, so A and G are correct. PrintStream and PrintWriter format text for a low-level OutputStream and Writer, respectively, so B and D are also correct. FileWriter and FileInputStream operate on a file directly and are lowlevel streams, so C and F are incorrect. Finally, OutputStream is an abstract parent class and is neither high-level nor low-level, so E is incorrect.

Which of the following stream classes are high-level? (Choose all that apply.) A. ObjectInputStream B. PrintStream C. FileWriter D. PrintWriter E. OutputStream F. FileInputStream G. ObjectOutputStream

A. The constructor for Console is private. Therefore, attempting to call new Console()outside the class results in a compilation error, making Option A the correct answer.The correct way to obtain a Console instance is to call System.console(). If the correct way of obtaining a Console had been used, and the Console was available at runtime, stuff is null in the printItinerary() method. Referencing stuff.activities results in a NullPointerException, which would make Option B the correct answer

public class Itinerary { private List<String> activities = new ArrayList<>(); private static Itinerary getItinerary(String name) { return null; } public static void printItinerary() throws Exception { Console c = new Console(); final String name = c.readLine("What is your name?"); final Itinerary stuff = getItinerary(name); stuff.activities.forEach( s -> c.printf(s) ); } public static void main(String[] holidays) throws Exception { printItinerary(); } } // What is the result of compiling and executing the program? A. The code does not compile. B. The code compiles and prints a NullPointerException at runtime. C. The code compiles but does not print anything at runtime. D. None of the above

C. The File getParent() method returns a String, not a File object. For this reason,the code does not compile on the last line since there is no getParent() method defined in the String class, and Option C is correct. If the first method call on the last line was changed to getParentFile(), then the code would compile and run without issue, outputting / - null and making Option B the correct answer. The File class does not require the location to exist within the file system in order to perform some operations, like getParent(), on the path.

public class Journey { public static void main(String[] dig) { File file = new File("/Earth"); System.out.print(file.getParent() +" - " + file.getParent().getParent() ); } } // Assuming the path /Earth does not exist within the file system, what is the output? A. / - / B. / - null C. The code does not compile. D. The code compiles but throws an exception at runtime.

C. The code compiles without issue, since InputStream and OutputStream both support reading/writing byte arrays, making Option A incorrect. Option D is also incorrect. While it is often recommended that an I/O array be a power of 2 for performance reasons, it is not required, making Option D incorrect. This leaves us with Options Band C. The key here is the write() method used does not take a length value, available in the chirps variable, when writing the file. The method will always write the entire data array, even when only a handful of bytes were read into the data array, which may occur during the last iteration of the loop. The result is that files whose bytes area multiple of 123 will be written correctly, while all other files will be written with extra data appended to the end of the file. For this reason, Option C is the correct answer. If the write(data) call was replaced with write(data,0,chirps), which does take the number of bytes read into consideration, then all files would copy correctly, making Option B the correct answer

public class Pidgin { public void copyPidgin(File s, File t) throws Exception { try( InputStream is = new FileInputStream(s); OutputStream os = new FileOutputStream(t) ) { byte[] data = new byte[123]; int chirps; while( (chirps = is.read(data) )>0 ) { os.write(data); } } } } // The copyPidgin() method is used to copy the contents of one file to another. Which statement about the implementation is correct? A. The class does not compile because read(byte[]) and write(byte[]) can only be called on BufferedInputStream and BufferOutputStream , respectively. B. The method correctly copies the contents of all files. C. The method correctly copies the contents of some files. D. The method will always throw an exception at runtime because the data array size is not a power of 2 .

A. The BufferedInputStream constructor in the readBook() method requires an InputStream as input. Since FileReader does not inherit InputStream, the readBook() method does not compile, and Option A is the correct answer. If FileReader was changed to FileInputStream, then the code would compile without issue. Since read() is called twice per loop iteration, the program would print every other byte, making Option C correct. Remember that InputStream read() returns -1 when the end of the stream is met. Alternatively, we use EOFException with ObjectInputStreamreadObject() to determine when the end of the file has been reached

public class Unicorn { public void findUnicorns() { try(InputStream o = new ObjectInputStream(readBook()) ) { while(o.read() != -1) { System.out.println(o.read()); } } catch (Throwable t) { throw new RuntimeException(t); } } private InputStream readBook() throws IOException { return new BufferedInputStream(new FileReader("magic.book")); } public static void main(String... horn) { new Unicorn().findUnicorns();} } // Which statement is true? A. The code does not compile. B. The program prints every byte in the file without throwing an exception. C. The program prints every even byte in the file without throwing an exception. D. The program throws an EOFException when the end of the file is reached.

A,B,C The name and age are both transient, their values will not be saved upon serialization. Upon deserialization, the default initializations and constructor will be skipped, and they will both be null. D is also incorrect because a serialized empty array is not the same as a null pointer. Even though these non-transient fields could be set to null, they are not guaranteed to be null after deserialization. E is incorrect because the static value will not be serialized; it will be available on the class after deserialization

public class Zebra implements Serializable { private static final long serialUID = 1L; private transient String name = "George"; private static String birthPlace = "Africa"; private transient Integer age; private java.util.List<Zebra> friends = new java.util.ArrayList<>(); private Object tail = null; { age = 10;} public Zebra() { this.name = "Sophia"; } } // Which fields will always be null after is serialized and then deserialized? (Choose all.) A. name B. tail C. age D. friends E. birthPlace

A. The code compiles and runs without issue. The first two values of theByteArrayInputStream are read. Next, the markSupported() value is tested. Since -1 isnot one of the possible answers, we assume that ByteArrayInputStream does supportmarks. Two values are read and three are skipped, but then reset() is called, puttingthe stream back in the state before mark() was called. In other words, everythingbetween mark() and reset() can be ignored. The last value read is 3

public int getWidgetNumber(byte[] data) throws Exception { try ( InputStream is = new ByteArrayInputStream(data) ) { is.read(new byte[2]); if( !is.markSupported() ) return -1; is.mark(5); is.read();is.read(); is.skip(3); is.reset(); return is.read(); } } // What is the output of the application if invoked with new byte[] {1,2,3,4,5,6,7} A. 3 B. 5 C. 7 D. An exception is thrown at runtime.

E, G. Not all java.io streams support the mark() operation; therefore, without calling markSupported() on the stream, the result is unknown until runtime. If the stream does support the mark() operation, then the result would be XYZY, because the reset() operation puts the stream back in the position before the mark() was called, and skip(1) will skip X, and E would be correct. If the stream does not support the mark() operation, a runtime exception would likely be thrown, and G would be correct.

public static String pullBytes(InputStream is, int count) throws IOException { is.mark(count); final StringBuilder sb = new StringBuilder(); for(int i=0; i<count; i++) sb.append( (char)is.read() ); is.reset(); is.skip(1); sb.append( (char)is.read() ); return sb.toString(); } // What possible output if the InputStream=XYZABC and a count=3? (all) A. It will return a String value of XYZ. B. It will return a String value of XYZA. C. It will return a String value of XYZX. D. It will return a String value of XYZB. E. It will return a String value of XYZY. F. The code does not compile. G. The code compiles but might throws an exception at runtime. H. The result cannot be determined with the information given.

C. The code contains two compilation errors. First, the File list() method returns a list of String values, not File values, so the call to deleteTree() with a String value does not compile. Either the call would have to be changed to f.listFiles() or the lambda expression body would have to be updated to deleteTree(new File(s)) for the code to work properly. Next, there is no deleteDirectory() method in the File class. Directories are deleted with the same delete() method used for files, once they have been emptied. With those two sets of corrections, the method would compile and be capable of deleting a directory tree. Notice we continually used the phrase "capable of deleting a directory tree." While the corrected code is able to delete a directory tree, it may fail in some cases, such as if the file system is read-only.

public void deleteTree(File f) { if( !f.isDirectory() ) f.delete(); else { Stream.of( *f.list()* ) .forEach( s -> deleteTree(s) ); *f.deleteDirectory()*; } } // Which of the following statements about the deleteTree() method is correct? A. It compiles and is capable of deleting a directory tree. B. If one line were modified, it might be capable of deleting a directory tree. C. If two lines were modified, it might be capable of deleting a directory tree. D. None of the above

B. All these methods correctly write strings and other objects to the underling writers. And PrintWriter have a constructor with Writer (like PrintStream has a constructor with underlining OutputStream)

try ( PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("zoo.log"))) ) { // *s1* out.print("Today's weather is: "); out.println("Sunny"); out.print("Today's temperature is: "); out.print(1/3.0); // *s2* out.println('C'); out.format("It has rained"); // *s3* out.println(); out.printf("It may rain 21.2 more"); // *s4* out.write("And we don't need to flush"); // *s5* } // What the result of run the application? (Choose all) A. IOException B. It compiles and successfully write data into file. C. It won't compile because of string s1 D. It won't compile because of s2 E. It won't compile because of s3 F. It won't compile because of s4 G. It won't compile because of s5


संबंधित स्टडी सेट्स

Class 4: Information Technology General Controls (ITGCs)

View Set

Chapter 8 Part 1 Practice Questions (Mobile Devices)

View Set

Chap. 22: peripheral vascular system

View Set

2.02 Mix and Match (Nature of Product Mix)

View Set

New Testament Survey: Chapter 11: John

View Set