How to Create a File in Java?

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

Files are an integral part of everyone’s life, not just for programmers but also normal users. Files can be used to store, organize and edit data. In java, creating a file is easier than one can imagine. There are three ways in which we can create a file in Java. In this article, we will take a look at all those methods at length.

Different ways to create a file in Java:

Java has various predefined classes and packages that contain methods to make creating files as simple as it can get. There are three methods to create a file in Java, they are as follows:

  • By Using File.createNewFile() method
  • Using FileOutputStream class
  • By Using File.createFile() method

Let us discuss them one by one.

1. Using File.createNewFile() method:

The File.createNewFile() method is part of the File class of the java.io package. The method doesn’t accept any arguments and has a return type of boolean. It returns true if the file is created and false if the file with the same name already exists.

The File.createNewFile() also throws I/O Exception if there is an exception during the creation of the file. It can also throw a SecurityException if the system has a security manager. Its SecurityManager.checkWriter(java.lang.String) method denies write access to the file.

We have to provide the file name and absolute or relative path of the file while creating the File object. If no path is mentioned the file is created in the PWD(Present Working Directory).

The signature of the method is:

public boolean createnewFile() throws IOException

Code to understand the working of File.createNewFile() method:

package com.DataFlair.FileCreation;
import java.io.*;
public class createNewFile_Method
{
    public static void main(String[] args)   
    {     
        File file_create = new File("G:\\Internship\\File Creation\\NewTextFile1.txt");
        boolean success;  
        try   
        {  
            success = file_create.createNewFile();
        if(success)  
        {  
            System.out.println("The File "+file_create.getCanonicalPath()+" is created!!!"); 
        }  
        else  
        {  
            System.out.println("The File already exist at location: "+file_create.getCanonicalPath());  
        }  
        }   
        catch (IOException e)   
        {  
            e.printStackTrace();
        }         
    }  
}

The output of the above code:

The File G:\Internship\File Creation\NewTextFile1.txt is created!!!
createnewfile

So, from the above image, it is clear that the file has been created successfully.

Explanation:
1. We first create a File class object, here I have given it the name file_create, you can give any name.

2. Now we create a boolean variable that will store the return value of the createNewFile() method.

3. Now we check if the result is true or false. If it is true that means the file is created, otherwise, the file was not created.

4. We use the try-catch block to handle the exception thrown by the method.

2. Using FileOutputStream class:

The FileOutputStream class is part of the java.io package. It is generally used to write in a file. However, if the file doesn’t exist in the mentioned path, a file by the given name is created for the purpose of writing in it. The FileOutputStream class provides a constructor that is used to create and write in a file.

The function signature of the constructor is:

public FileOutputStream(String name, boolean append) throws FileNotFoundException  

The Parameter name contains the file name and the parameter append will write at the end of the file if its value is true, and if it is false it will write at the beginning.

Code to understand the working of FileOutputStream class:

package com.DataFlair.FileCreation;
import java.io.*;
import java.util.*;
public class FileOutputStream_class
{
    public static void main(String args[])  
    {  
        try  
        {  
            Scanner sc=new Scanner(System.in);
            System.out.print("Enter the file name: ");  
            String fname=sc.nextLine();               
            FileOutputStream file_create=new FileOutputStream(fname, true);  
            System.out.print("Enter the content of the file: ");         
            String str=sc.nextLine()+"\n";     
            byte[] b= str.getBytes();       
            file_create.write(b);           
            file_create.close();           
            System.out.println("File is saved in the given location!!!!");  
        }  
        catch(Exception e)  
        {  
            e.printStackTrace();          
        }  
    }  
}

The output of the above code:

Enter the file name: G:\Internship\File Creation\NewTextFile2.txt
Enter the content of the file: This file is created with FileOutputStream class
File is saved in the given location!!!!

fileoutputstreamclass

From the above image, we can see that the file is created in the given location successfully.

file at location

This image shows the content of the file.

Explanation:
1. We use the utility scanner to take input from the user regarding the name of the file and its content.

2. We then create an object of the FileOutputStream class and pass the argument with the file name and true/false as per our requirement.

3. After that, we enter the content of the file.

4. Then the content is converted to bytes, as FileOutputStream is a byte stream.

5. We then write the bytes onto the file and close it.

6. The whole thing is done inside a try-catch block to handle the exceptions thrown.

3. Using File.createFile() method:

The File.createFile() is a method that is part of the File class of the java.nio package. The nio package is a buffer-oriented package. It also provides support for files. The method createFile() creates a new and empty file. Unlike other methods, the resources need not be closed in this method.

The signature of this method is:

public static Path createFile(Path, Attribute) throws IOException  

The path parameter is to enter the path of the file and the attribute method is to enter an optional list of file attributes.
The method returns the created file.

Before writing the code, one particular line requires some information:

Path path = Paths.get("G:\\Internship\\File Creation\\NewTextFile3.txt");

In the above line of code, Path is an interface and Paths is a class. The Paths.get() method creates an instance of Path and is given the name path.

Code to understand the working of File.createFile() method:

package com.DataFlair.FileCreation;
import java.nio.file.*;
import java.io.*;
public class createFile_Method
{
    public static void main(String[] args)   
    {  
        Path path = Paths.get("G:\\Internship\\File Creation\\NewTextFile3.txt"); 
        try   
        {  
            Path file_path= Files.createFile(path); 
            System.out.println("File Created at "+file_path+" Successfully!!!");  
        }   
        catch (IOException e)   
        {  
            e.printStackTrace();  
        }  
    }  
}

The output of the above code:

File Created at G:\Internship\File Creation\NewTextFile3.txt Successfully!!!
createfile method

From the above image, we can see that the file is created in the given location successfully.

Explanation:
1. At first, we create the Path instance.
2. The file is created using the createFile() method in the specified location.
3. We use the try-catch block to handle the exception.

Conclusion:

So, in this article, we saw how we can create a file fairly easily using java. The methods provided by java makes file creating really simple. It also gives the programmer an option to choose from the various methods it has. So, making the job of the programmer easy and simple.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

Leave a Reply

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