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 File class. In this class we have createNewFile() method which returns a boolean value.

If file is created it returns true. Returns false, if file already exists or failed due to some error.

You can also read – Create Directory Java Program

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

Let’s take a look on how to create a new file in java,

Example: create file java program

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

public class CreateFile
{
   public static void main(String[] args)
   {
      try
      {
         File fl = new File("C:/createfile.txt");
         if(fl.createNewFile())
         {
            System.out.println("File created");
         }
         else
         {
            System.out.println("File exists");
         }
      }
      catch(IOException ioe)
      {
         ioe.printStackTrace();
      }
   }
}

Output:

File created


Java create new file using FileOutputStream.write() method

Here I’m going to show you how to create a file in java using 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());
   }
}


Conclusion

That’s it guys. This is all about how to create a file in java. I hope you have understood the concept.

You can subscribe to my blog flower brackets if you haven’t already.

Do share this article if you like.

Related Posts