Create a New File in Java

A file is a great way to store a large amount of data you can use later whenever needed! In this post, we’ll look at different ways to create files in Java. All we need to do is import the relevant package and use the relevant methods.

We can create a New File in Java in different ways, that is:

  • Create a File with java.io.file class.
  • Using java.io.fileOutputStream
  • Create File with java.nio Package
Post On:Create a New File in Java
Post Type:Java Tutorials
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:SoftwareTestingo Telegram Group

Create a New File with the java.io.file class.

In Java, the most commonly used file creation method is the createNewFile() method of the java.io.File class. This method creates a new file in Java and returns a boolean value. To use this method, initialize an object of the File class with the name of the file you wish to create and then call the createNewFile()method on that object.

If the file is successfully created, this method returns true. If the file with the given name already exists, it returns false. This method also throws java.io.IOException if there’s an error during file creation.

package com.SoftwareTestingO.IO;
import java.io.File;
import java.io.IOException;
public class CreateNewFile 
{
	public static void main(String[] args) 
	{
		File file = new File("e://newFile.txt");

		try 
		{
			if (file.createNewFile()) 
			{
				System.out.println("File create");
			}
			else
			{
				System.out.println("File already exists!");
			}
		} 
		catch (IOException e) 
		{
			System.out.println(e.getMessage());
		}
	}
}

Note: The above example creates an empty file in the provided location.

Creating java file using java.io.FileOutputStream class

This is another method you can use to create a file in Java. This class creates a new file at the specified path and also allows you to write or add content to it so that it can serve two purposes at the same time.

The fileName is the name of the file that we want to create. If true, we pass a boolean value as the second parameter, which will append content to the end of the file.

package com.SoftwareTestingO.IO;
import java.io.FileOutputStream;
import java.util.Scanner;
public class CreateNewFile1 
{
	public static void main(String[] args) 
	{
		try 
		{
			//object of Scanner class    
			Scanner sc = new Scanner(System. in ); 
			System.out.print("Enter the file name with specific location: ");

			//variable name to store the file name 
			String name = sc.nextLine();  
			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("The file has been saved on the given path.");
		}
		catch(Exception e) 
		{
			System.out.println("Exception Occurred:");
			e.printStackTrace();
		}
	}
}

Note: When using fileOutputStream, pass in false as a parameter if the file already exists and contains data. Otherwise, the data will be overwritten and lost!

Creating Java file using Java NIO Files.createFile() method

Use the java.nio package to create files, which was introduced in JDK 7. To create a file with the nio package, set the path and use the createFile() method from the Files class. Creating files via the new nio package is preferred because the API is more intuitive.

package com.SoftwareTestingO.IO;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateNewFile2 
{
	public static void main(String[] args) 
	{
		//creates Path instance
		Path path = Paths.get("e:\\MyFile.txt");   
		try 
		{
			//creates file at specified location  
			Path p = Files.createFile(path); 
			System.out.println("File Created at Path: " + p);
		}
		catch(IOException e) 
		{
			System.out.println("Exception Occurred:");
			e.printStackTrace();
		}
	}
}

Conclusion:

This article looked at different solutions for creating a file in Java. We used classes from the JDK as well as external libraries.

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment