How To Create A File In Java

In Java, creating a file is easy by using pre-defined classes and packages. There are three ways to create a file.

  • Using File.createNewFile method
  • Using FileOutputStream class
  • Using File.createFile method

Java File.createNewFile method

The method File.createNewFile is a function within the File class in the java.io package. It operates without any parameters. This function is responsible for generating a fresh, vacant file. Upon execution, it provides a boolean outcome:

  • true: denoting successful creation of the file.
  • false: indicating that the file already exists.

To create a new file in Java, we can instantiate a File class object with the desired file name and subsequently invoke the createNewFile method of the File class.

When the File.createNewFile method encounters an I/O error, it raises a java.io.IOException. Additionally, if a security manager is present and its SecurityManager.checkWriter(java.lang.String) method refuses write permissions to the file, it throws a SecurityException. The method is defined by the following signature:

Example

public boolean createNewFile() throws IOException

The File class object can accept either the file name, absolute path, or relative path as an argument. When a non-absolute path is provided, the File object will attempt to find the file within the current directory.

Example

In the provided demonstration, a fresh text file is generated. During the initial execution, the file named music.txt is successfully established; however, it encounters an error during the subsequent run. By solely modifying the file extension, various file types can be generated.

Example

import java.io.File;

import java.io.IOException;

public class CreateFileExample1 

{

public static void main(String[] args) 

{	

File file = new File("C:\\demo\\music.txt"); //initialize File object and passing path as argument

boolean result;

try 

{

result = file.createNewFile();	//creates a new file

if(result)		// test if successfully created a new file

{

System.out.println("file created "+file.getCanonicalPath()); //returns the path string

}

else

{

System.out.println("File already exist at location: "+file.getCanonicalPath());

}

} 

catch (IOException e) 

{

e.printStackTrace();	//prints exception if any

}		

}

}

Output

When file does not exists.

When file already exists.

Java FileOutputStream

An Output stream for files is responsible for writing data to a file. In Java, the FileOutputStream class is utilized for file operations and is part of the java.io package. This class specifically deals with storing data in the form of bytes. When there is a requirement to input data into a newly generated file, the FileOutputStream class becomes essential. To instantiate a file using the FileOutputStream class, a constructor is provided with the following signature:

Example

public FileOutputStream(String name, boolean append) throws FileNotFoundException

Parameters

name: is the file name

If the condition is met, a byte will be added to the end of the file rather than at the beginning.

Example

In this instance, a file has been generated utilizing FileOutputStream.

Example

import java.io.FileOutputStream;

import java.util.Scanner;

public class CreateFileExample

{

public static void main(String args[])

{

try

{

Scanner sc=new Scanner(System.in);         //object of Scanner class

System.out.print("Enter the file name: ");

String name=sc.nextLine();				//variable name to store the file name

FileOutputStream fos=new FileOutputStream(name, true); 	// true for append mode

System.out.print("Enter file content: ");		

String str=sc.nextLine()+"\n";		//str stores the string which we have entered

byte[] b= str.getBytes();		//converts string into bytes

fos.write(b);			//writes bytes into file

fos.close();			//close the file

System.out.println("file saved.");

}

catch(Exception e)

{

e.printStackTrace();		

}

}

}

Output

Java File.createFile method

The createFile method is a part of the File class within the java.nio.file package, offering file support in a buffer-oriented manner. This method serves the purpose of generating a new, blank file without the necessity to manage resource closure manually, which is a notable convenience. Its method signature is as follows:

Example

public static Path createFile(Path, Attribute) throws IOException

Path: The path of the file.

Attribute: An optional list of file attributes.

The method returns the file.

An additional instance is demonstrated here, generating a fresh, vacant file. By utilizing the Paths class (java.nio.file.Paths) and its static method Paths.get, a Path object is instantiated. Consider the subsequent declaration:

Create a Path object by using the Paths class's get method and passing the file location "C:\\demo\\javaprogram.txt" as a parameter. This will represent the file path for the specified file in the system.

The statement above highlights that "Path" functions as an interface, while "Paths" operates as a class within the identical package. The creation of a Path Instance is facilitated by the "Paths.get" method.

Example

import java.io.IOException;

import java.nio.file.*;

public class CreateFileExample3

{

public static void main(String[] args) 

{

Path path = Paths.get("C:\\demo\\javaprogram.txt"); //creates Path instance

try 

{

Path p= Files.createFile(path);		//creates file at specified location

System.out.println("File Created at Path: "+p);

} 

catch (IOException e) 

{

e.printStackTrace();

}

}

}

Output

Input Required

This code uses input(). Please provide values below: