views:

70

answers:

4

Hi,

when I write this piece of

String path="d:\\test.txt";
    boolean chk;
    File f=new File(path);

    try
    {
        chk=f.createNewFile();
    }catch(IOException e)
    {
        chk=false;
        e.printStackTrace();
    }


    if(chk)
        System.out.println("file created.");
    else
        System.out.println("file not created");

file is created in d-drive

but when I use this

String path="d:\\test.txt";
    File f=new File(path);

    if(f.createNewFile())
        System.out.println("file created.");
    else
        System.out.println("file not created");

it throws exception.

Please enlighten me on this

+3  A: 

I doubt that the second piece of code actually "throws an exception"; most likely what you are seeing is a compile error warning you that you must catch the checked exception IOException when you call createNewFile.

A "checked" exception must have a handler or be declared by the calling method via throws, or your code will not compile. IOException is checked. createNewFile declares that it throws IOException. Therefore your second block of code is not correct.

Borealid
A: 

I guess you get an IO exception or you cannot create (write) that file, maybe because it's opened.

thelost
A: 

File.createNewFile() throws an exception if the file already exists (or you don't have the right to create the file). So after running the first piece of code... the second will fail, if you forgot to delete test.txt.

Gabor Kulcsar
Sir I guess in that case o/p will be "File not created."But the code will surely run.
Ankit Sachan
It will only run if it compiles, and your second example doesn't compile.
EJP
@Ankit @EJP some IDE's have a configuration setting which allows you to run the code anyway in spite of compilation errors (the red marks). Truly the code won't always run successfully due to compilation errors. @Ankit: you need to ensure that you get rid of red marks before you run the code in Eclipse. They are not for decoration :) Click the bullets for a list of possible solutions.
BalusC
A: 

Change second part of you code to following:

                    String path = "d:\\test.txt";
                    File f = new File(path);

                    try {
                        if (f.createNewFile())
                            System.out.println("file created.");
                        else
                            System.out.println("file not created");
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }

You are required to do this because if you don't surrond f.createNewFile() within try/catch block, your code won't compile. As usage of f.createNewFile() throws IOException you need to either put it in try/catch block catching IOException or method using this part of code needs to declare throws IOException.

YoK
dude I guess this is what I did in first snippet :-)
Ankit Sachan