Assuming the working directory is accessible, empty, and able to be written, how many file system objects does the following class create?
1: package mypkg; 2: import java.io.*; 3: public class Main { 4: public static void main(String... tooMany) throws IOException { 5: File f = new File("f.txt"); 6: Writer w = new FileWriter("w.txt"); 7: w.flush(); //from ww w . j a va 2s. c o m 8: new File("s.txt").mkdirs(); 9: } 10:}
C.
Line 5 creates a File object, but that does not create a file in the file system unless f.createNewFile()
is called.
Line 6 also does not necessarily create a file, although the call to flush()
will on line 7.
Note that this class does not properly close the file resource, potentially leading to a resource leak.
Line 8 creates a new File object, which is used to create a new directory using the mkdirs()
method.
Recall from your studies that mkdirs()
is similar to mkdir()
, except that it creates any missing directories in the path.
Since directories can have periods (.) in their name, such as a directory called info.txt, this code compiles and runs without issue.
Since two file system objects, a file and a directory, are created, Option C is the correct answer.