St.Antario St.Antario - 1 month ago 20
Java Question

Does creating a new File instance cause creating an empty file?

I read the

File
class javadoc. Here is what's written there:


Creates a new File instance by converting the given pathname string
into an abstract pathname. If the given string is the empty string,
then the result is the empty abstract pathname.


QUESTION: Is it guarantee that if file doesn't exist it won't create an empty file or it depends on the system? I tried it on RedHat linux and an empty file is created only after I create
OutputStream
.

It's not obvious from java to me.

Answer

Yes, it's guaranteed that the file won't be created by calling new File(). It'll be created if you call createNewFile().

The pattern might be:

File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) { 
    // do something
} else {
    f.createNewFile();
}