Java create new file

Let’s learn java create new file.

java create new file

Creating file in java

Creating a new file in the java program is very common in java interview question.

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

Also read – HashSet in java

In creating a file, first create File object then call createNewFile() method to create new file.

File createNewFile() method returns true if file is created, else returns false. If File createNewFile() method is not able to create new file then java.io.IOException is thrown.

Let’s see java program to create a new file in java,

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(byte[] b) method

Here I’m going to show FileOutputStream.write(byte[] b) method. FileOutputStream.write(byte[] b) method writes data into it. Let’s see java program on FileOutputStream.write(byte[] b) method,

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 NIO Files.write() method is, you need not have an overhead of closing input/output resources.

Here’s java program,

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());
   }
}