Java create file

Today we are going to learn java create file.

java create file

To create file java program we need createNewFile() method of java.io.File class which creates empty file and returns a boolean value.

Also read – create directory java program

If a new file is created it returns true, 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());
   }
}

Related Posts