Java create new file

Today we are going to learn java create new file.

java create file

There are few methods to create file in java one of them is createNewFile() method of java.io.File class which creates empty file and returns a boolean value.

Also read – create directory java program

This method returns true if file is created, else returns false. If this method is not able to create new file then java.io.IOException is thrown. Here’s the code,

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

public class DemoCreate
{
   public static void main(String[] args) throws IOException
   { 
      try 
      {
         File file = new File("D:\\demo.txt"); 
         boolean bool = file.createNewFile();
         if(bool)
         {
            System.out.println("File created successfully");
         }
         else
         {
            System.out.println("File already exists");
         }
      }
      catch(IOException ex)
      {
         System.out.println("Exception : ");
         ex.printStackTrace();
      }
   }
}


Using FileOutputStream.write() method

Here I’m going to show FileOutputStream.write() method. This method meanwhile write data into it.

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

public class Example
{
   public static void main(String[] args) throws IOException
   {
      String strFile = "Flower Brackets";
      FileOutputStream file = new FileOutputStream("demo.txt");
      file.write(strFile.getBytes());
      file.flush();
      file.close();
   }
}


Using NIO Files.write() method

Like FileOutputStream.write() method, write() method of NIO Files class can be used to create and write data into file.

Best thing about write() method is, you need not have an overhead of closing input/output resources. Here’s the code,

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

public class Demo 
{
   public static void main(String[] args) throws IOException 
   {
      String strFile = "Flower Brackets";
      Files.write(Paths.get("demo.txt"), strFile.getBytes());
   }
}