Search This Blog

Saturday, August 6, 2011

OCPJP(SCJP1.6) Question 30

   1: import java.io.File;
   2: import java.io.IOException;
   3:  
   4: /**
   5:  * Created by IntelliJ IDEA.
   6:  * User: Owner
   7:  * Date: 8/6/11
   8:  * Time: 12:57 PM 
   9:  */
  10: public class TestCreateNewFile {
  11:     public static void main(String[] args) throws IOException {
  12:         File f = new File("scjp6exam.txt");
  13:         System.out.println(f.exists());
  14:         f.createNewFile();
  15:         System.out.println(f.exists());
  16:     }
  17: }

Options :

A. Prints “ false, false”.

B. Prints “ false, true”

C. Can throw an exception at Line 14.

D. Line 15 may not be executed.


Answer : B, C, D

 

A is incorrect because after creating a file in line 14 f.exists() returns if the file has been created successfully. However f.createNewFile() can throw an IOException for many reason. One of such could be creating a file in a read-only directory. If the exception is thrown then line 15 does not get executed. So C and D are also correct.

 

File –> createNewFile() Java 1.6 API


public boolean createNewFile()
                      throws IOException


Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.

Note: this method should not be used for file-locking, as the resulting protocol cannot be made to work reliably. The FileLock facility should be used instead.






Returns:
true if the named file does not exist and was successfully created; false if the named file already exists
Throws:
IOException - If an I/O error occurred
SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method denies write access to the file



 
OCPJP(SCJP1.6) Question 30SocialTwist Tell-a-Friend

2 comments:

  1. I am so glad atlast I found this answer. I am founding this answer from a 2 days even I asked my few friends to help me out in this but still I can't get it well. Now I was finding online and I found your blog on google and i got my answer and I am so happy. Thanks for sharing this.
    Best regards
    Moscow mules

    ReplyDelete
  2. A friend ask me this question last monday, and finally i will help him. I will share this post with him and he will be happy after having this.

    Thanks for sharing

    Best regards
    Erie Tree Trimmers
    tree stump removal erie pa

    ReplyDelete