Java OCA OCP Practice Question 3043

Question

Consider the following code snippet.

String srcFile = "Hello.txt";
String dstFile = "World.txt";

try (BufferedReader inputFile = new BufferedReader(new FileReader(srcFile));
      BufferedWriter outputFile = new BufferedWriter(new FileWriter(dstFile))) {
    int ch = 0;//from w  w w.jav  a 2  s  .c  o m
    inputFile.skip(6);
    while( (ch = inputFile.read()) != -1) {
        outputFile.write( (char)ch );
    }
    outputFile.flush();
} catch (IOException exception) {
    System.err.println("Error " + exception.getMessage());
}

Assume that you have a file named Hello.txt in the current directory with the following contents:.

Hello World!

Which one of the following options correctly describes the behavior of this code segment (assuming that both srcFile and dstFile are opened successfully)?.

  • a)the program will throw an IOException because skip() is called before calling read()
  • b)the program will result in creating the file World.txt with the contents "World!" in it
  • c)this program will result in throwing CannotSkipException
  • d)this program will result in throwing IllegalArgumentException


b)

Note

the method call skip(n) skips n bytes (i.e., moves the buffer pointer by n bytes).

In this case, 6 bytes need to be skipped, so the string "hello" is not copied in the while loop while reading and writing the file contents.

option a) the skip() method can be called before the read() method.

option c) No exception named CannotSkipException exists.

option d) the skip() method will throw an IllegalArgumentException only if a negative value is passed.




PreviousNext

Related