How To Create a New File

In this section we will discuss about how to create a new file in Java.

How To Create a New File

In this section we will discuss about how to create a new file in Java.

How To Create a New File

How To Create a New File

In this section we will discuss about how to create a new file in Java.

A Computer File is a storage of data. In this file we can store String, characters, numbers etc. In Java to create a File for storing the data we can use the constructor and methods of java.io.File class. Such as, File.createNewFile() method creates the new file. java.io.File creates the new file with the abstract directory path names. To specify the name and directory of file the pathname contains the following two components :

  • System dependent prefix (optional) i.e. ' / ' used for specifying the root directory in UNIX or, ' \\ ' used for specifying the root directory in Windows and
  • zero or more string names.

For detail description of java.io.File you can see the Java docs or click here.

Example

Here I am giving a simple example which will demonstrate you about how to create a new file in Java. In this example I have created a Java class where used the constructor and methods of java.io.File class. In this class I have used File(String pathname) constructor which specifies the file name/pathname and createNew() method which creates the new file with the specified name/pathname. In this example a file name can be given as command line argument and if the file existed already in the specified directory then the it will shows a message that a ' File is existed already' otherwise a file with the specified name/pathname will be created.

Source Code

import java.io.File;
public class JavaCreateNewFileExample
{
    public static void main(String args[])
      {
           String fileName = args[0];
           File file = new File(fileName);
              if(file.exists())
                {
                   System.out.println("\n File '"+file.getName()+"' already existed");
                }
              else
                {
                   try
                     {
                         file.createNewFile();
                         System.out.println("\n File '"+file.getName()+ "' created successfully ");
                     }
                    catch(Exception e)
                     {
                        System.out.print(e);
                     }
                }
      }// main() closed
}// class closed

Output

When you will execute the above example you will get the output as follows :

1. When you will execute this example first time and the file doesn't exists in the specified directory then the output will be as follows :

2. When you will execute this example second time and the file is created in the first time or the file with the specified name is existed already then the output will be as follows :

Download Source Code