Create file java program

Hey guys!! Welcome to flower brackets blog. Today we are going to learn create file java program.

Create File Java Program

In java, we have few methods to create a new file. Among them is java.io.File class. In this class we have createNewFile() method which creates empty file and returns a boolean value.

Please note: that createNewFile() method will only create a file not writing.

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

Also read – create directory java program

Here’s the code,

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

public class CreateFileDemo
{
   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();
      }
   }
}


Java create new file using FileOutputStream.write() method

Here I’m going to show FileOutputStream.write() method. Using this method you can create new file and write data into it.

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

public class CreateFileExample
{
   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();
   }
}


Java create new file using NIO Files.write() method

Like FileOutputStream.write() method, write() method of NIO Files class can be used to create new file 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 CreateNewFileDemo 
{
   public static void main(String[] args) throws IOException 
   {
      String strFile = "Flower Brackets";
      Files.write(Paths.get("demo.txt"), strFile.getBytes());
   }
}

Related Posts