How to Create File In Java

Creating files in java is important operations for developing applications . We can create file in java using pre defined methods . In this tutorial we will see how to create a file in java using java.io.file, java.io.fileOutputStream, and java.nio packages . So these are ways to create file in java

  1. Create File with java.io.File class
  2. Using java.io.fileOutputStream
  3. Create File with java.nio Package

Create File with java.io.File class

We can use java.io.File class for create file in java . We will use createNewFile() method of File class to create new file. First we create object of File Class and pass path with name of file inside constructor of object . After that we will call cretaeNewFile() method and it creates a new, empty file named by given pathname if and only if a file with this name does not yet exist.

Syntax :

public boolean createNewFile(){
}

Return Value : It is return true if the named file does not exist and was successfully created otherwise  false if the named file already exists .

Exception : It throws following exceptions                                                                    IOException – If an I/O error occurred during creation of file .
SecurityException – This exception occur If a security manager exists and its java.lang.SecurityManager.checkWrite(java.lang.String) method denies write access to the file

Now we will see how to create new file in java using java.io.File.createNewFile() method .

package com.demo.file;
import java.io.File;
import java.io.IOException;

public class CreateFileJavaExamples {
	public static void main(String[] args) {
                //create file object with  file path
		File file = new File("C://java_examples//newFile.txt");
		try {
			if (file.createNewFile()) { //return true if file created 
                               //otherwise return flase
				System.out.println("File create");
			} else { 
				System.out.println("File already exists!");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

If we use invalid path then it will throw java.io.IOException . In below example we use invalid path which does not exits .

package com.demo.file;
import java.io.File;.
import java.io.IOException;

public class CreateFileJavaExamples {
	public static void main(String[] args) {
		File file = new File("C://java_//newFile.txt");
		try {
			if (file.createNewFile()) {
				System.out.println("File create");
			} else {
				System.out.println("File already exists!");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Output :

java.io.IOException: The system cannot find the path specified
	at java.io.WinNTFileSystem.createFileExclusively(Native Method)
	at java.io.File.createNewFile(Unknown Source)
	at com.demo.file.CreateFileJavaExamples.main(CreateFileJavaExamples.java:11)

So be careful when creating file you must have to use valid path .

Create File Using java.io.FileOutputStream

In this example we use Fileoutputstream class to create file in java . Fileoutputstream class have multiple constructors , we use FileOutputStream(String name, boolean append) constructors to create file .

Syntax :

public FileOutputStream(String name, boolean append) throws FileNotFoundException

Parameter :

Name : name of the file                                                                                                        append : if true, then bytes will be written to the end of the file not in the beginning

Exceptions :

FileNotFoundException – If the file exists but directory not , cannot be created, or cannot be opened for any other reason
SecurityException – If a security manager exists and its checkWrite method denies write access to the file.

Let’s see example for Fileoutputstream class

package com.demo.file;

import java.io.FileOutputStream;

public class CreateFileJavaExamples2 {
	
	public static void main(String[] args) {
		 try {
	            new FileOutputStream("C://java_examples//newFile1.txt", true);
	            System.out.println("file created successfully");
	        } catch (Exception e) {
	        	e.printStackTrace();
	        }
	}
}

Create File with java.nio Package

We can create file using createFile() metho of java.nio.file.Files class . In this example first we will set path of file with the help of java.nio.file.Path object after that we will create file using createFile() method of Files class .

Syntax :

public static Path createFile(Path path, FileAttribute<?>... attrs)
        throws IOException

Parameter :

path :  The path of the file
attrs : An optional list of file attributes .

Return value :  This method return file .

Exception : It is throws following exceptions                                                UnsupportedOperationException – It thows if the attr array contains an attribute that cannot be set atomically when creating the file .
FileAlreadyExistsException – if a file name already exists .
IOException – if an I/O error occurs or the parent directory does not exist
SecurityException – In the case of the default provider, and a security manager is installed, the checkWrite method is invoked to check write access to the new file.

package com.demo.file;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CreateFileJavaExamples3 {
	public static void main(String[] args) {
		
		 try {
	            Path newFilePath = Paths.get("C://java_examples//newFile3.txt");
	            Files.createFile(newFilePath);
	            System.out.println("File Created Successfully");
	        }catch (IOException e) {
	        	e.printStackTrace();
	        }
	}

}

We have learned different method for creating files in java . You can see more java file handling examples .

Javadoc: createNewFile()

Leave a Reply

Your email address will not be published. Required fields are marked *

19 − = 12