Java create new file

Let’s learn java create new file.

Java create new file

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.

java create new file

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

File class 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.

Also read – how to create directory in java

Let’s see an example on createNewFile() method of File class.

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 b.length bytes from the specified byte arrayto this file output stream.

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 on NIO Files.write() method.

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



create file if not exist

Let’s learn to create file if not exist using FileOutputStream class.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class CreateFileIfNotExist 
{
   public static void main(String[] args) 
   {
      File fl = new File("java/createFile.txt");
      try 
      {
         // do nothing if file exists 
         if(fl.createNewFile()) 
         {
            // create new empty file
            FileOutputStream fos = new FileOutputStream(fl, false);
            // write some date to file
            String strData = "create file example";
            fos.write(strData.getBytes());
            fos.close();
            System.out.println("createFile.txt file is created!");
         } 
         else 
         {
            System.out.println("createFile.txt file already exists!");
         }
      } 
      catch(IOException ex) 
      {
         System.out.println(ex.getMessage());
      }
   }
}


Output:

createFile.txt file is created!


java program to write into a text file

To write into a text file use PrintWriter class. Here’s the java program to write into a text file.

import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteIntoTextFile 
{
   public static void main(String[] args) throws FileNotFoundException 
   {
      PrintWriter player = new PrintWriter("names.txt");
      // writing cricket player name into the file
      player.println("virat");
      player.println("dhoni");
      player.println("rohit");
      player.println("jadeja");
      player.close();
   }
}


Output:

virat
dhoni
rohit
jadeja


java read file

To read file we are using scanner class. Let’s learn how to read file in java.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class JavaReadFile 
{
   public static void main(String[] args) 
   {
      try
      {
         File obj = new File("fruitnames.txt");
         Scanner read = new Scanner(obj);
         while(read.hasNextLine()) 
         {
            String strData = read.nextLine();
            System.out.println(strData);
         }
         read.close();
      } 
      catch(FileNotFoundException ex) 
      {
         System.out.println("Error occurred.");
         ex.printStackTrace();
      }
   }
}


Output:

apple
orange
banana
pineapple


java delete file

To delete a file in java delete() method of File class is used. delete() method deletes the file or directory denoted by this abstract pathname.

If this pathname denotes a directory, then the directory must be empty inorder to be deleted.

delete() method returns true if and only if the file or directory is successfully deleted; false otherwise.

Here’s the program on delete a file in java.

import java.io.File;
public class JavaDeleteFile
{
   public static void main(String[] args) 
   {
      File fl = new File("C:\JavaProject\Sachin\demo.txt");
      if(fl.delete()) 
      { 
         System.out.println("File deleted successfully"); 
      } 
      else
      { 
         System.out.println("Failed to delete the file"); 
      }
   }
}


Output:

File deleted successfully