Java OCA OCP Practice Question 3277

Question

Which method implementation will write the given string to a file named "file", using UTF8 encoding?.

Select the one correct answer.

(a) public void write(String msg) throws IOException {
      FileWriter fw = new FileWriter(new File("file"));
      fw.write(msg);//from   w w w  .j av  a 2s  .co  m
      fw.close();
    }

(b) public void write(String msg) throws IOException {
      OutputStreamWriter osw = new OutputStreamWriter(
                                     new FileOutputStream("file"), "UTF8");
      osw.write(msg);
      osw.close();
    }

(c) public void write(String msg) throws IOException {
      FileWriter fw = new FileWriter(new File("file"));
      fw.setEncoding("UTF8");
      fw.write(msg);
      fw.close();
    }

(d) public void write(String msg) throws IOException {
      FilterWriter fw = new FilterWriter(
                             new FileWriter("file"), "UTF8");
      fw.write(msg);
      fw.close();
    }

(e) public void write(String msg) throws IOException {
      OutputStreamWriter osw = new OutputStreamWriter(
                                    new OutputStream(new File("file")), "UTF8");
      osw.write(msg);
      osw.close();
    }


(b)

Note

Method implementation (a) will write the string to the file, but will use the native encoding.

Method implementation (c) will fail to compile, since a method named setEncoding() does not exist in class FileWriter.

Method implementation (d) will fail to compile, since FilterWriter is an abstract class that cannot be used to translate encodings.

Method implementation (e) will fail to compile, since class OutputStream is abstract.




PreviousNext

Related