Java IO Tutorial

How to create a file in Java

In Java, there are many ways to create and write to a file.

  1. Files.newBufferedWriter (Java 8)
  2. Files.write (Java 7)
  3. PrintWriter
  4. File.createNewFile

Note
I prefer the Java 7 nio Files.write to create and write to a file, because it has much cleaner code and auto close the opened resources.


  Files.write(
        Paths.get(fileName),
        data.getBytes(StandardCharsets.UTF_8));

1. Java 8 Files.newBufferedWriter

1.1 This example shows how to use the new Java 8 Files.newBufferedWriter to create and write to a file.

CreateFileJava8.java

package com.mkyong.io.file;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CreateFileJava8 {

    public static void main(String[] args) {

        String fileName = "/home/mkyong/newFile.txt";

        Path path = Paths.get(fileName);

        // default, create, truncate and write to it.
        try (BufferedWriter writer =
                     Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {

            writer.write("Hello World !!");

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

        /* Append mode.
        try (BufferedWriter writer =
                     Files.newBufferedWriter(path,
                             StandardCharsets.UTF_8,
                             StandardOpenOption.APPEND)){

            writer.write("Hello World !!");

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

    }
}

2. Java 7 Files.write

2.1 This example shows how to use the Java 7 nio Files.write to create and write to a file.

By default, it opens a file for writing; create the file if it doesn’t exist; truncate the current content if the file exists.

CreateFileNio.java

package com.mkyong.io.file;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class CreateFileNio {

    public static void main(String[] args) {

        String fileName = "/home/mkyong/newFile.txt";
        String content = "hello world!";

        try {

            // Java 1.7
            // default, create and write to it.
            Files.write(
                    Paths.get(fileName),
                    content.getBytes(StandardCharsets.UTF_8));

            // Append content
            /*Files.write(
                    Paths.get(fileName),
                    content.getBytes(StandardCharsets.UTF_8),
                    StandardOpenOption.APPEND);*/

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

    }

}

2.2 Review the Files.write. source code; it uses the try-with-resources to auto-close the opened resources.

Files.java

package java.nio.file;

  public final class Files {

      public static Path write(Path path, byte[] bytes, OpenOption... options)
            throws IOException
      {
          // ensure bytes is not null before opening file
          Objects.requireNonNull(bytes);

          try (OutputStream out = Files.newOutputStream(path, options)) {
              int len = bytes.length;
              int rem = len;
              while (rem > 0) {
                  int n = Math.min(rem, BUFFER_SIZE);
                  out.write(bytes, (len-rem), n);
                  rem -= n;
              }
          }
          return path;
      }

      //...
  }

3. PrintWriter

3.1 This example shows how to use PrintWriter to create and write to a file.

CreateFile.java

package com.mkyong.io.file;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

public class CreateFile {

    public static void main(String[] args) {

        String fileName = "/home/mkyong/newFile.txt";

        // Java 10, new constructor, support Charsets
        try (PrintWriter writer = new PrintWriter(fileName, StandardCharsets.UTF_8)) {

            writer.println("first line!");
            writer.println("second line!");

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

        // Java 1.5
        /*try (PrintWriter writer = new PrintWriter(fileName, "UTF-8")) {

            writer.println("first line!");
            writer.println("second line!");

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

4. File.createNewFile()

4.1 This example shows how to use the File.createNewFile() to create an empty file, and the FileWriter to write data to the file.

CreateFile2.java

package com.mkyong.io.file;

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

public class CreateFile2 {

    public static void main(String[] args) {

        String fileName = "/home/mkyong/newFile.txt";

        try {

            File file = new File(fileName);

            // true if file does no exist and was created successfully.
            // false if file is already exists
            if (file.createNewFile()) {
                System.out.println("File is created!");
            } else {
                System.out.println("File already exists.");
            }

            // Write to file
            try (FileWriter writer = new FileWriter(file)) {
                writer.write("Hello World!");
            }

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

    }

}

Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-io

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
23 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
boris
8 years ago

It doesn’t work. new File(String) throws a NullPointerException which is not being caught in this example.

Dattz
6 years ago
Reply to  boris

Only throws NullPointerException if the passed argument is null.

varinder dua
8 years ago

nice article

Rohit More
9 years ago

how to create file within project folder like webContent?

shreya
9 years ago

thank yu
it helped in my exam

john
9 years ago

I copied your codes on eclipse but file doesn’t create
Can you help me!!!!

NISHIT PATIRA
9 years ago
Reply to  john

If you get the message that says “A required privelage does not exist”, change the file path from C:\newfile.txt to some place else. That may solve the problem.

imran
9 years ago

Can you tell me that if the user creates a file than again he want to create a new file again . by entering his own file url e.g newfile.txt …. please sir help me?

NISHIT PATIRA
9 years ago
Reply to  imran

It is not possible as the file already exists. You can create a new file in a separate folder by changing the path.

Mubeen
10 years ago

Thanks it cleared most of my doubts, but can u tell me what is the purpose of this “file.createNewFile”.

Guest
9 years ago
Reply to  Mubeen

hiiiiiiiiiii

prathmeshn
9 years ago
Reply to  Mubeen

If doesnt exist it creates new file

Oleg Derecha
10 years ago

Thanks, it helped to overcome/solve problem FileNotFoundException in IntelliJ IDEA

IT and Non IT Jobs
10 years ago

Very simple example for Java beginners.

owenbowen
10 years ago

i get an error saying access denied

amit
10 years ago

Must Read

amit
10 years ago

Good Tutorial

ryan
10 years ago

Hello mates, its fantastic article on the topic of cultureand
entirely defined, keep it up all the time.

raghu
11 years ago

showing command like do without try and catch

keren happuch
11 years ago

“enter the file name to be created” i want write the prg for this? if anyone know pls help

Racha Suman
11 years ago

your doing very well for creating good JAVA Programmers by learning from ur Website sir,,,,,,,,
i likes ur website a lot and as well as u….
From Racha Suman, India

Tlhologelo
11 years ago

The tutorials would be good with documentation/comments there is really no beginner who can grasp this stuff all at once.

ashish
11 years ago

I want to know is this a static page or dynamically generated