The Wayback Machine - https://web.archive.org/web/20240930173251/https://www.geeksforgeeks.org/java-program-to-create-a-new-file/
Open In App

Java Program to Create a New File

Last Updated : 11 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A File is an abstract path, it has no physical existence. It is only when “using” that File that the underlying physical storage is hit. When the file is getting created indirectly the abstract path is created. The file is one way, in which data will be stored as per requirement.

Steps to Create a New File in Java

1. Primary, in order to create a new file, inbuilt files, and functions are used which definitely will throw Exceptions here playing it safe. So in order to deal with it, we will be using Exception Handling Techniques. Here, we will use one of them known try-catch block techniques. 

2. Secondary, additional work is simply we will be importing File Class for which we will be importing File Class.

File object_name = new File(Directory)

Methods to Create a New File in Java

There are two standard methods to create a new file either directly with the help of File class or indirectly with the help of FileOutputStream by creating an object of the file in both approaches.

  • By using File Class
  • By using the FileOutputStream Class

Both classes provide some methods which are mainly used to do operations regarding files.

For example, to create, to write, to compare two path names, to check whether a specific file is present or not, and many more. To understand this topic, first, consider one example for both approaches.

1. Java Program to Create a new file using the File class 

It is a class that is just a handle for underlying file system resources. It is used for those objects which do not have physical existence.

Syntax:

File.createNewFile()

Below is the implementation of the topic:

Java




// Java Program to create new file using File class
 
// Importing new files
import java.io.File;
import java.io.BufferedReader;
 
// Importing as it converts bits to strings
import java.io.InputStreamReader;
 
public class GFG {
 
    // Main Driver Method
    public static void main(String args[])
    {
        // Creating New File via function
        GFG gfg = new GFG();
        gfg.newFile();
    }
 
    // Function To Make New File
    public void newFile()
    {
        String strPath = "", strName = "";
 
        // Try-catch Block
        try {
 
            // Creating BufferedReadered object
            BufferedReader br = new BufferedReader(
                new InputStreamReader(System.in));
            System.out.println("Enter the file name:");
 
            // Reading File name
            strName = br.readLine();
            System.out.println("Enter the file path:");
 
            // Reading File Path
            strPath = br.readLine();
 
            // Creating File Object
            File file1
                = new File(strPath + "" + strName + ".txt");
 
            // Method createNewFile() method creates blank
            // file.
            file1.createNewFile();
        }
 
        // Try-Catch Block
        catch (Exception ex1) {
        }
    }
}


Output:  

Output of using File Class method

Name of file to be added  : newFile.txt
Directory where file is to be added : /Users/mayanksolanki/Desktop/Folder/

File Created using File Class

Added file name            : newFile.txt
Added file name directory : /Users/mayanksolanki/Desktop/Folder/

Explanation of the above Program:

  1. To create a new file using java language, the “File” class is used here. “BufferedReader” and “InputStreamReader” both classes are used to make file names and paths from the user as input. These classes are located inside the “java.io” package. So to make use of those classes, it is necessary to import those classes at the beginning of the program.
  2. Here class is created namely, “GFG”. And inside that class “main()” method is defined from which execution will be started.
  3. Inside the “main()” method object of the class is created. And this object is used to call the “newFile()” method.
  4. Outside of the main() method, the newFile() method is declared which is covers code for taking input from the user and create the file as per input.
  5. As the file have its own name and path, it is necessary to give a name for the file (which we want to create) and a path (where to create the file) for the file. In this line, two blank strings are declared namely, strName, strPath. “strName, and strPath are used to store the name and path of the file when the user gives this information.
  6. To take file name and path from the user as input, here BufferedReader class and InputStreamReader class are used. The object of BufferedReader “br” is useful to take input values given by the user.
  7. This line print some text to give an indication to the user like ”Enter the file name:”. To print the text “println()” function is used.
  8. Here “readLine()” method is used to take input and store it, in strName and strPath.
  9. Here object of the File class is created and as a parameter, the file path and name are given to the constructor. In this line of code “.txt” is a format of the file. You can change it as per need. The object of the File class is necessary to call methods provided in its class.
  10. Here “createNewFile()” method is called with the help of the File class object. This method creates a blank file on a given directory path.
  11. Lastly, enclosed by “try{ }” block. Because, methods like readLine() and createNewFile() methods generates exception. So to handle that exception try, the catch is used.

2. How to Create a new file in Java using FileOutputStream class?

It is an output stream that can be written to FileOutputStream JavaDoc. It is used for those objects which are already existing.

Syntax:

FileOutputStream 

Example: echo > myFile.txt

Below is the implementation of the FilesOutputStream Class:

Java




// Java Program to create new file
// using FileOutputStream class
 
// Importing File Classes
import java.io.FileOutputStream;
 
// Importing BufferedReader Class for taking input
import java.io.BufferedReader;
 
// Importing as it converts bits to strings
import java.io.InputStreamReader;
 
// Function Helping Create New File
public class GFG {
 
    // Main Driver Method
    public static void main(String args[])
    {
        // Creating File Object
        GFG gfg = new GFG();
        gfg.newFile();
    }
 
    // Function To Create A New File
    public void newFile()
    {
        String strFilePath = "", strFileName = "";
 
        // Try-Catch Block
        try {
 
            // Creating BufferClass Object
            BufferedReader br = new BufferedReader(
                new InputStreamReader(System.in));
            System.out.println("Enter the file name:");
 
            // Asking file name from User
            strFileName = br.readLine();
            System.out.println("Enter the file path:");
 
            // Asking file path from User
            strFilePath = br.readLine();
 
            // Creating Object of FileOutputStream Class
            FileOutputStream fos = new FileOutputStream(
                strFilePath + "" + strFileName + ".txt");
        }
 
        // Try-Catch Block
        catch (Exception ex1) {
        }
    }
}


 Output: It will be the same as the previous one because just the approach to create a new file has changed the rest of the file name and the directory where it is added remains the same.

Added file name            : newFile.txt
Added file name directory : /Users/mayanksolanki/Desktop/Folder/

Output of using FileOutputStream Class

Explanation of the above Program:

In the second example, the File class is not used to create a new File programmatically. 

  1. To create a new file using java language, “FileOutputStream” class is used here and “BufferedReader” &  “InputStreamReader” both are used to take file name and path from the user as input. These classes are located inside of “java.io” package. So to make use of those classes, it is necessary to import them at the beginning of the program.
  2. Class is created namely, “GFG”. And inside that class “main()” method is defined from which execution will be started.
  3. Inside of “main()” method object of the class is created. And this object is used to call the “newFile()” method.
  4. Outside of the main() method, the newFile() method is declared which is covers code for taking input from the user and create a file as per input.
  5. In this line, two blank strings are declared namely, strFileName, strFilePath. “strFileName and strFilePath are used to store the name and path of the file when the user gives this information.
  6. To take file name and path from the user as input, here BufferedReader class and InputStreamReader class are used. The object of BufferedReader “br” is useful to take input values given by the user.
  7. This line print some text to give an indication to the user like ”Enter the file name:”. To print text “println()” function is used.
  8. Here “readLine()” method is used to take input and store it, in strFileName and strFilePath.
  9. Here object of FileOutputStream class is created and as a parameter, file path and name are given to the constructor. In this line of code “.txt” is a format of the file. You can change it as per need. The object of FileOutputStream class is necessary to call methods provided in its class. For example, if the user wants to store some text in a newly created file programmatically then, the write() method is helpful.
  10. Lastly, enclosed by “try{ }” block. Because, readLine() method generates exception. So to handle that exception try, catch block is used.

Note: To specify a directory is different in different operating systems (suppose a java file is in a folder named ‘Folder’ is created on the desktop)

In Linux and Mac
/Users/mayanksolanki/Desktop/Folder/

In Windows: ‘ \\ ‘ used instead of  ‘ / ‘ to escape ‘ \ ‘ character. So the same directory is accessed as
\\Users\\mayanksolanki\\Desktop\\Folder\\



Previous Article
Next Article

Similar Reads

How to Create a File with a Specific File Attribute in Java?
In Java, you can create a file with specific File attributes such as read-only, hidden, or system attributes. This allows you to control the behavior and visibility of the file in the File system. In this article, we'll explore how to create a file with specific attributes in Java. In this article, we will learn to create a file with a specific fil
2 min read
Java Program to Read Content From One File and Write it into Another File
File handling plays a major role in doing so as the first essential step is writing content to a file. For this is one must know how to write content in a file using the FileWriter class. The secondary step is reading content from a file and print the same. For this, one must have good hands on File Reader class to do so. Now in order to read conte
5 min read
Java Program to Create a Temporary File
A File is an abstract path, it has no physical existence. It is only when "using" that File that the underlying physical storage is hit. When the file is getting created indirectly the abstract path is getting created. The file is one way, in which data will be stored as per requirement. Type of File .txt.tmp (Default File Type)Primary, in order to
5 min read
Java Program to Create String from Contents of a File
A File is a computer resource which is deployed to store different types of data such as text, image, video, to name a few. It is basically a collection of data bound to a single entity. While using your computer, it becomes essential to be able to deal with files and in this article we will be learning about various ways to read data from files. W
6 min read
How to Create and Modify Properties File Form Java Program in Text and XML Format?
Properties file are a text-oriented key value a pair of contents present in a Java project with .properties extension. Line by line, the key-value pair of contents are present, and they are usually prepared by means of notepad, Wordpad, EditPlus, etc., Properties files are usually helpful to store important sensitive information and in this article
5 min read
Java Program to Create a File in a Specified Directory
Creating a file in a specific directory using Java can be done in various ways. This is done using predefined packages and Classes. In this article, we will learn about how to create a file in a specified directory. Methods to Create a File in a Specified DirectoryThree such methods to create a file in a specified directory are mentioned below: Fil
3 min read
How to Create a .exe File From a Java Program?
In this article, we will learn how to create a .exe file from a Java program. Java is a platform-independent language, which works on the philosophy of "write Once, Run Anywhere". It simply means that if we write a Java program, we can run it on any device that has a JVM(Java Virtual Machine). Now if we want to share the Java application standalone
5 min read
Java Program to Create a File with a Unique Name
Java Programming provides a lot of packages for handling real-time problems but in our case, we need to create a File with a unique name. For this, there are different solutions in Java. Like Using timestamp series as the file name or creating a unique random number and then assigning that number as a file name. In this article, we will learn two d
6 min read
How to Execute SQL File with Java using File and IO Streams?
In many cases, we often find the need to execute SQL commands on a database using JDBC to load raw data. While there are command-line or GUI interfaces provided by the database vendor, sometimes we may need to manage the database command execution using external software. In this article, we will learn how to execute an SQL file containing thousand
5 min read
Different Ways to Copy Content From One File to Another File in Java
In Java, we can copy the contents of one file to another file. This can be done by the FileInputStream and FileOutputStream classes. FileInputStream Class It is a byte input stream class which helps in reading the bytes from a file. It provides different methods to read the data from a file. FileInputStream fin = new FileInputStream(filename); This
3 min read
How to Convert a Kotlin Source File to a Java Source File in Android?
We use Android Studio to translate our Java code into Kotlin while transitioning from Java to Kotlin. But what if we need to convert a Kotlin file to its Java equivalent? We'll examine how to convert a Kotlin source file to a Java source file in this blog. Let's get this party started. Because of its interoperability with Java, Kotlin grew at an ex
2 min read
How to Extract File Extension From a File Path String in Java?
In Java, working with Files is common, and knowing how to extract file extensions from file paths is essential for making informed decisions based on file types. In this article, we will explore techniques for doing this efficiently, empowering developers to improve their file-related operations. Program to extract file extension from a file path S
5 min read
Java Program to Insert a New Node at the Beginning of the Circular Linked List
Circular linked list: A circular linked list is a sequence of elements in which every element points to its next element in the sequence and the last element has a link to the first element. That means a circular linked list is similar to the single linked list except that the last node points to the first node in the list. Inserting a new node at
4 min read
Java Program to Insert a New Node at the Middle of the Circular Linked List
Given a Circular Linked List, the task is to add a New Node at the Middle of the List. Let's consider the following Circular Linked List: Create a new node (New_node).Check for an empty list. If the list is empty then insert the node as head.For non-empty list, calculate the length of the list. Create variable mid and store middle length in it.Crea
3 min read
Java Program to Merge Two Sorted Linked Lists in New List
We are given two sorted List and our goal is to merge these two lists into a new list. For that, we have to write one function which will take two List as an argument which is sorted in increasing order. This function will Merge these two List into one List in increasing order. Input List 1 : 1-> 3-> 4-> 9->10 List 2 : 2-> 5-> 6-
4 min read
Java Program to Print a New Line in String
Java is the most powerful programming language, by which we can perform many tasks and Java is an industry preferable language. So it is filled with a huge amount of features. Here we are going to discuss one of the best features of Java, that is how to print a new line in a string using Java. Methods: There are many ways to print new line in strin
3 min read
Java JDK 21: New Features of Java 21
Hey, Java enthusiasts and learners! Java is the most trending language in the world, which attracts the population or you can say Java techies towards its simplicity and its super features with vast functionalities. So to make the development more interesting for Java developers, Java is again here with its evolving new features and functionalities
11 min read
Java Program to Extract Content from a Java's .class File
In this article, we are going to extract the contents of the Java class file using the Apache Tika library. Apache Tika is used for document type detection and content extraction from various file formats. It uses various document parsers and document type detection techniques to detect and extract data. It provides a single generic API for parsing
2 min read
How to Create New ImageView Dynamically on Button Click in Android?
In this article, we are going to implement a very important feature related to ImageView. Here we are going to add ImageView dynamically. We will be just changing the background color. Whenever we click on a button a new ImageView will be created. So here we are going to learn how to implement that feature. A sample video is given below to get an i
3 min read
Android - Create a New Playlist in Your Spotify Account using Spotify Web API
Spotify is one of the world's most popular music streaming platforms, and it has a vast collection of songs, albums, playlists, and podcasts. With the Spotify Web API, developers can create amazing applications that interact with the Spotify service. Using the Web API's endpoints, one can get detailed metadata about artists, albums, and tracks dire
13 min read
Create a Temporary File in Java
In Java, we can create a temporary file using an existing method known as File.createTempFile() method which creates a new empty file on the specified directory. The createTempFile() function creates a temporary file in a given directory (if the directory is not mentioned then a default directory is selected), the function generates the filename by
4 min read
Create Password Protected Zip File in Java
Primarily, java does not have any function or package that will create a password-protected zip file without using some native codes. Java has some useful library which is good but they use some native codes to perform their task that makes their usage platform dependent to some extent. Whereas in the zip4j library we are just using java code witho
5 min read
How to Create Jar File for Java Project in Eclipse?
Java programmers already know about what is a jar file if you are new then first understand what is a jar file. Once you are completed your project in Eclipse the next task is to create a runnable version of your project. Eclipse support only exporting the JAR (.jar) file, not the Executable (.exe) file. It is very important to learn as a Java prog
3 min read
How to Create a File with a Specific charset in Java?
In Java, when we write text to a file, we must provide the character encoding to create a file with a specified charset. Classes to generate Java Files with Specified CharsetUsing a FileOutputStream and the OutputStreamWriter class we can generate a Java file with a specified charset. FileOutputStream: It is an OutputSream class used for storing da
2 min read
How to Create and Manipulate a Memory-Mapped File in Java?
The Memory-mapped files in Java offer a powerful mechanism to map a region of a file directly into the memory providing efficient access to file data. This method enhances the performance when dealing with large files or when frequent access to the file data is required. Syntax:The key method involved in the memory mapping of a file in Java is File
2 min read
How to Create a File with a Specific Owner and Group in Java?
Java is a basic tool that does not directly let you choose who owns a file or which group it belongs to when you create it. You have to rely on other methods or external libraries if you need to control these aspects. In this article, we will learn How to create a file with a specific owner and group in Java. Approaches to Create a File with Specif
3 min read
New Date-Time API in Java 8
New date-time API is introduced in Java 8 to overcome the following drawbacks of old date-time API : Not thread safe : Unlike old java.util.Date which is not thread safe the new date-time API is immutable and doesn't have setter methods.Less operations : In old API there are only few date operations but the new API provides us with many date operat
6 min read
Merge Arrays into a New Object Array in Java
Given two arrays of the same type, they need to be merged into a new object array. The task is to merge the two arrays of the same type into an object array such that the array elements maintain their original order in the newly merged array and the elements of the first array precede the elements of the second array in the merged object array. Thi
6 min read
New Features of Java 12
Oracle released Java SE(Standard Edition) 12 on March 19, 2019, after which they plan to have a new release every six months. JDK 12 came with a lot of improvements over JDK 11. This latest version offers a list of new features such as Switch Expressions, Default CDS Archives, Shenandoah, Microbenchmark Suite, among others. These new features are d
7 min read
JDK 17 - New Features in Java 17
Java 17 LTS is the latest long-term support release for the Java SE platform. JDK 17 binaries are free to use in production and free to redistribute, at no cost, under the Oracle No-Fee Terms and Conditions License, where LTS stands for long-term support. It was released on September 15, 2021. Have you ever wondered What do we mean by this? Without
7 min read
Practice Tags :