Java – Create new file

There are many ways to create a file in java. Creating a file is a very easy task. We will learn 5 different ways to Create a file.
[toc]

Using java.io.File class’s createNewFile method

This is simplest and oldest way to create file.Here is simple snapshot to create a file in java.


package org.arpit.java2blog;

import java.io.File;
import java.io.IOException;

public class CreateFileMain {

    public static void main(String[] args) {
        try {

              File file = new File("c://newJava2blogfile.txt");

              if (file.createNewFile()){
                System.out.println("File is created!");
              }else{
                System.out.println("File already exists.");
              }

            } catch (IOException e) {
              e.printStackTrace();
        }
    }
}

Using java.nio.file.Files from JDK 7

This is preferred way of creating file after JDK 7 on wards. Please note that it will throw FileAlreadyExistsException in case file already present.

package org.arpit.java2blog;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CreateFileMain {

    public static void main(String[] args) {
        Path newFilePath = Paths.get("C://newJava2blogFile_jdk7.txt");
        try {
            Files.createFile(newFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using java.io.FileOutputStream

You can use FileOutputStream’s write method to create new file and write content to it.

package org.arpit.java2blog;

import java.io.FileOutputStream;
import java.io.IOException;

public class CreateFileMain {

    public static void main(String[] args) throws IOException {
        String data = "Java writing to file";
        FileOutputStream out = new FileOutputStream("c://testJava2blog.txt");
        out.write(data.getBytes());
        out.close();
    }
}

Using guava library

Here is simple way to create file using following oneliner.

Files.touch(new File("c://newJava2blogFile_guava.txt"));

Using Common IO library

Here is another way to create new file using Common IO library. Please note that it does nothing if file alreay exists. It is similar to touch command in linux.

Files.touch(new File("c://newJava2blogFile_commonUtil.txt"));

That’s all about Java-create new file.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.