Java OCA OCP Practice Question 1896

Question

The copyMain() method is used to copy the contents of one file to another.

Which statement about the implementation is correct?

package mypkg; /*  w  ww. j av a  2 s  .  c om*/
import java.io.*; 
public class Main { 
   public void copyMain(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); 
         }} 
   }
} 
  • A. The class does not compile because read(byte[]) and write(byte[]) can only be called on BufferedInputStream and BufferedOutputStream, 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.


C.

Note

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 B and 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 are a multiple of 123 will be written correctly, while all other files will be written with extra data appended to the end of the file.

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.




PreviousNext

Related