java.io.File createNewFile()
Description
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
Method Syntax
public boolean createNewFile() throws IOException
Method Argument
Data Type | Parameter | Description |
---|---|---|
N/A | N/A | N/A |
Method Returns
This method returns boolean, true if the named file does not exist and was successfully created; false if the named file already exists. This is in place so that you have a way to determine if the creation of file is successful or not and act accordingly.
Compatibility
Requires Java 1.2 and up
Java File createNewFile() Example
Below is a java code demonstrates the use of createNewFile() method of File class. The example presented might be simple however it shows the behaviour of the createNewFile() method of File class. Basically we called this method and we put a check on the returned value to check if the creation of new file is successful or not.
The example provided below shows that on the first run, the file has been created successfully while on the second run it failed. That is because the file is already created on the first run, thus succeeding run will definitely fail as describe on the earlier part of this document.
package com.javatutorialhq.java.examples; import java.io.File; import java.io.IOException; /* * This example source code demonstrates the use of * createNewFile() method of File class. * */ public class FileCreateNewFileExample { public static void main(String[] args) { // initialize File object File file = new File("C:javatutorialhqinput.txt"); boolean result; try { // create a new file result = file.createNewFile(); // test if successfully created a new file if(result){ System.out.println("Successfully created "+file.getCanonicalPath()); } else{ System.out.println("Filed creating "+file.getCanonicalPath()); } } catch (IOException e) { e.printStackTrace(); } } }