my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes createNewFile() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "createNewFile()" Watch "createNewFile()" New topic
Author

createNewFile()

fengqiao cao
Ranch Hand

Joined: Oct 26, 2001
Posts: 71
hi, there
i know the delete()of File class can delete the file or directory existing on the underlining System. How about createNewFile()? Dose it create a file on the underling system?( i know we can't do that by creating an instance of File class)
thanks in adv....
Uma Viswanathan
Ranch Hand

Joined: Jun 14, 2001
Posts: 126
Yes. createFile() will create a new empty file, if the file does not exist.
Checking for existence and creating a new file is atomic.
The security manager's (if there is one) checkWrite() method is called to check for write permission
So, this method throws IOException (if an I/O error occurred) and SecurityException
If the file does not exist and successfully created, then it returns true. If the file already exists, then it returns false.
Check this code...
File f = new File("Test.java");
if( f.exists() )
System.out.println( "File already exists" );
try{
f.createNewFile();
}
catch( IOException e )
{}
if( f.exists() )
System.out.println( "Successfully created" );
Hope this helps...
Uma
fengqiao cao
Ranch Hand

Joined: Oct 26, 2001
Posts: 71
Hi, Uma
thanks for your reply
But what are saying is not enought to prove that createNewFile()has already created a file on the underling system.
if i am wrong , please correct me!!!
Uma Viswanathan
Ranch Hand

Joined: Jun 14, 2001
Posts: 126
Check the concept with the code what i have given...
File f = new File("Test101.java");
if( f.exists() )
System.out.println( "Before create: File already exists" );
else
{
System.out.println( "Before create: File does not exist...going to create one" );
try{
f.createNewFile();
}
catch( IOException e )
{}
if( f.exists() )
System.out.println( "After create:Successfully created" );
else
System.out.println( "After create:Could not create" );
}
Note:
Before you run this code, make sure that you do not have Test101.java in the directory from where you are going to execue this code.
You could also physically verify your directory that after running this code, you will have the new file created...I had already verified...
fengqiao cao
Ranch Hand

Joined: Oct 26, 2001
Posts: 71
Uma
thanks very much.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: createNewFile()