file creation using java code example

Example 1: Java create new file

// example on createNewFile() method of File class in java
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();
      }
   }
}

Example 2: java create file

String fileData = "yourContent";
FileOutputStream fos = new FileOutputStream("yourFile.txt");
fos.write(fileData.getBytes());
fos.flush();
fos.close();

Tags:

Java Example