What is the output of the following application?
It is safe to 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.
package mypkg; //w ww . java 2s . c o m import java.io.*; public class Main { public void m() 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) { try { new Main().m(); } catch (Exception e) { new RuntimeException(e); } } }
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.
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.
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.
Our program ends without throwing any exceptions, and Option C is the correct answer.