• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

  • Home
  • Interview Questions
  • Java
  • Java Programs
  • Selenium
  • Selenium Programs
  • Manual Testing
  • Test Cases
  • Difference
  • Tools
  • SQL
  • Contact Us
  • Search
SoftwareTestingo » Java » Java Tutorial » Create a New File in Java

Create a New File in Java

Last Updated on: May 22, 2022 By Softwaretestingo Editorial Board

What We Are Learn On This Post

  • Create New File with the java.io.file class
  • Creating java file using java.io.FileOutputStream class
  • Creating Java file using Java NIO Files.createFile() method

A file is a great way to store a large amount of data that you can use later whenever you need it! 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 with below different ways, that are:

  • Create 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 New File with the java.io.file class

In Java, the most commonly used method for creating a file is to use 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, simply 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.

Java Tutorial
  • Java List
  • Java Set
  • Java ArrayList
  • SortedSet In Java
  • Java HashSet
  • Java String split() Method
  • Java String compareTo() Method
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 it can serve two purposes at the same time.

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

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, be careful to 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, first set the path and then 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();
		}
	}
}

Copnclusion:

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

    Filed Under: Java Tutorial

    Reader Interactions

    Leave a Reply Cancel reply

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

    Primary Sidebar

    Join SoftwareTestingo Telegram Group

    Categories

    Copyright © 2022 SoftwareTestingo.com ~ Contact Us ~ Sitemap ~ Privacy Policy ~ Testing Careers