Java OCA OCP Practice Question 2470

Question

Given the following XML, which code options, when inserted at //INSERT CODE HERE, will write this XML (in exactly the same format) to a text file?.

<emp>
<id>1234</id>
<name>Harry</name>
</emp>
class Main{
    public void writeEmpData() throws IOException{
        File f = new File("empdata.txt");
        PrintWriter pw = null;
    //INSERT CODE HERE
        pw.close();
    }
}
a  pw = new PrintWriter(f);
   pw.println("<emp>");
   pw.write("<id>");
   pw.writeInt(1234);// ww w .java2s  .  c o  m
   pw.println("</id>");
   pw.print("<name>Harry</name>");
   pw.print("</emp>");
   pw.flush();

b  pw = new PrintWriter(new FileOutputStream(f));
   pw.write("<emp>");
   pw.write("<id>1234</id>");
   pw.write("<name>Harry</name>");
   pw.write("</emp>");
   pw.flush();

c  pw = new PrintWriter(f);
   pw.println("<emp>");
   pw.println("<id>1234</id>");
   pw.println("<name>Harry</name>");
   pw.println("</emp>");
   pw.flush();

d  pw = new PrintWriter(new FileOutputStream(f));
   pw.println("<emp>");
   pw.println("<id>1234</id>");
   pw.println("<name>Harry</name>");
   pw.println("</emp>");
   pw.flush();


c, d

Note

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).




PreviousNext

Related