Tutorial

Java create new file

Published on August 3, 2022
author

Pankaj

Java create new file

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Creating a file is a very common IO operation. Today we will look into different ways to create a file in java.

Java create file

java create file, java create new file There are three popular methods to create file in java. Let’s look at them one by one.

  1. File.createNewFile()

    java.io.File class can be used to create a new File in Java. When we initialize File object, we provide the file name and then we can call createNewFile() method to create new file in Java. File createNewFile() method returns true if new file is created and false if file already exists. This method also throws java.io.IOException when it’s not able to create the file. The files created is empty and of zero bytes. When we create the File object by passing the file name, it can be with absolute path, or we can only provide the file name or we can provide the relative path. For a non-absolute path, File object tries to locate files in the project root directory. If we run the program from command line, for the non-absolute path, File object tries to locate files from the current directory. While creating the file path, we should use System property file.separator to make our program platform independent. Let’s see different scenarios with a simple java program to create a new file in java.

    package com.journaldev.files;
    
    import java.io.File;
    import java.io.IOException;
    
    public class CreateNewFile {
    
        /**
         * This class shows how to create a File in Java
         * @param args
         * @throws IOException 
         */
        public static void main(String[] args) throws IOException {
            String fileSeparator = System.getProperty("file.separator");
            
            //absolute file name with path
            String absoluteFilePath = fileSeparator+"Users"+fileSeparator+"pankaj"+fileSeparator+"file.txt";
            File file = new File(absoluteFilePath);
            if(file.createNewFile()){
                System.out.println(absoluteFilePath+" File Created");
            }else System.out.println("File "+absoluteFilePath+" already exists");
            
            //file name only
            file = new File("file.txt");
            if(file.createNewFile()){
                System.out.println("file.txt File Created in Project root directory");
            }else System.out.println("File file.txt already exists in the project root directory");
            
            //relative path
            String relativePath = "tmp"+fileSeparator+"file.txt";
            file = new File(relativePath);
            if(file.createNewFile()){
                System.out.println(relativePath+" File Created in Project root directory");
            }else System.out.println("File "+relativePath+" already exists in the project root directory");
        }
    
    }
    

    When we execute the above program from Eclipse IDE for the first time, the below output is produced.

    /Users/pankaj/file.txt File Created
    file.txt File Created in Project root directory
    Exception in thread "main" 
    java.io.IOException: No such file or directory
    	at java.io.UnixFileSystem.createFileExclusively(Native Method)
    	at java.io.File.createNewFile(File.java:947)
    	at com.journaldev.files.CreateNewFile.main(CreateNewFile.java:32)
    

    For the relative path, it throws IOException because tmp directory is not present in the project root folder. So it’s clear that createNewFile() just tries to create the file and any directory either absolute or relative should be present already, else it throws IOException. So I created “tmp” directory in the project root and executed the program again, here is the output.

    File /Users/pankaj/file.txt already exists
    File file.txt already exists in the project root directory
    tmp/file.txt File Created in Project root directory
    

    First two files were already present, so createNewFile() returns false, third file was created in tmp directory and returns true. Any subsequent execution results in the following output:

    File /Users/pankaj/file.txt already exists
    File file.txt already exists in the project root directory
    File tmp/file.txt already exists in the project root directory
    

    If you run the same program from terminal classes directory, here is the output.

    //first execution from classes output directory	
    pankaj:~/CODE/JavaFiles/bin$ java com/journaldev/files/CreateNewFile
    File /Users/pankaj/file.txt already exists
    file.txt File Created in Project root directory
    Exception in thread "main" java.io.IOException: No such file or directory
    	at java.io.UnixFileSystem.createFileExclusively(Native Method)
    	at java.io.File.createNewFile(File.java:947)
    	at com.journaldev.files.CreateNewFile.main(CreateNewFile.java:32)
    
    //tmp directory doesn't exist, let's create it
    pankaj:~/CODE/JavaFiles/bin$ mkdir tmp
    
    //second time execution
    pankaj:~/CODE/JavaFiles/bin$ java com/journaldev/files/CreateNewFile
    File /Users/pankaj/file.txt already exists
    File file.txt already exists in the project root directory
    tmp/file.txt File Created in Project root directory
    
    //third and subsequent execution
    pankaj:~/CODE/JavaFiles/bin$ java com/journaldev/files/CreateNewFile
    File /Users/pankaj/file.txt already exists
    File file.txt already exists in project root directory
    File tmp/file.txt already exists in project root directory
    
  2. FileOutputStream.write(byte[] b)

    If you want to create a new file and at the same time write some data into it, you can use FileOutputStream write method. Below is a simple code snippet to show it’s usage. The rules for absolute path and relative path discussed above is applicable in this case too.

    String fileData = "Pankaj Kumar";
    FileOutputStream fos = new FileOutputStream("name.txt");
    fos.write(fileData.getBytes());
    fos.flush();
    fos.close();
    
  3. Java NIO Files.write()

    We can use Java NIO Files class to create a new file and write some data into it. This is a good option because we don’t have to worry about closing IO resources.

    String fileData = "Pankaj Kumar";
    Files.write(Paths.get("name.txt"), fileData.getBytes());
    

That’s all for creating a new file in the java program.

You can checkout more core java examples from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
June 4, 2019

very long code

- naina

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    March 13, 2019

    why this below code is not creating the file in server. I have deployed this code on server. import java.io.IOException; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; public class WriteIntoFile { void FileWriter(String txt) throws IOException { /*String csvFilePath = “output_file.csv”; // String csvFilePath = “/root/Desktop/Workspace/myProjects/output_file.csv”; OutputStream os = Files.newOutputStream(Paths.get(csvFilePath), StandardOpenOption.WRITE); Writer outputStreamWriter = new OutputStreamWriter(os); String header[] = { “name”, “state”, “corrId”, “projType” }; CSVPrinter csvPrinter = new CSVPrinter(outputStreamWriter, CSVFormat.DEFAULT.withHeader(header)); csvPrinter.printRecord(txt); csvPrinter.flush(); csvPrinter.close();*/ } }

    - Saas

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      October 18, 2018

      nice explenenton and thancc for sharing my friend …i wish goood flfill you all wishes…

      - blyat

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 5, 2018

        I executed the program but it is giving exception access denied How to solve it

        - jasreen

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          March 22, 2016

          nice explanation and thanx for sharing …………i wish good fulfill you all wishes………

          - Ravinder

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            June 8, 2014

            nice explanation and thanx for sharing …i wish good fulfill you all wishes…

            - vikas rana

              Try DigitalOcean for free

              Click below to sign up and get $200 of credit to try our products over 60 days!

              Sign up

              Join the Tech Talk
              Success! Thank you! Please check your email for further details.

              Please complete your information!

              Featured on Community

              Get our biweekly newsletter

              Sign up for Infrastructure as a Newsletter.

              Hollie's Hub for Good

              Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

              Become a contributor

              Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

              Welcome to the developer cloud

              DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

              Learn more
              DigitalOcean Cloud Control Panel