Java Examples - New File Creation


Advertisements


Problem Description

How to create a new file ?

Solution

This example demonstrates the way of creating a new file by using File() constructor and file.createNewFile() method of File class.

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

public class Main {
   public static void main(String[] args) {
      try {
         File file = new File("C:/myfile.txt");
         
         if(file.createNewFile())System.out.println("Success!");
         else System.out.println ("Error, file already exists.");
      }
      catch(IOException ioe) {
         ioe.printStackTrace();
      }
   }
}

Result

The above code sample will produce the following result (if "myfile.txt does not exist before)

Success!

The following is an another sample example of File create

import java.io.IOException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import java.util.Arrays;
import java.util.List;

public class JavaApplication1 { 
   public static void main(String[] args) throws IOException {
      createFileUsingFileClass();
      createFileUsingFileOutputStreamClass();
      createFileIn_NIO();
      // TODO code application logic here
   } 
   private static void createFileUsingFileClass() throws IOException { 
      File file = new File("c://testFile1.txt");
      
      //Create the file
      if (file.createNewFile()) { 
         System.out.println("File is created!");
      } else {
         System.out.println("File already exists.");
      } 
      
      //Write Content
      FileWriter writer = new FileWriter(file);
      writer.write("Test data");
      writer.close();
   } 
   private static void createFileUsingFileOutputStreamClass() throws IOException { 
      String data = "Test data";
      FileOutputStream out = new FileOutputStream("c://testFile2.txt");
      out.write(data.getBytes());
      out.close();
   } 
   private static void createFileIn_NIO()  throws IOException { 
      String data = "Test data";
      Files.write(Paths.get("c://testFile3.txt"), data.getBytes());
      List<String> lines = Arrays.asList("1st line", "2nd line");
      Files.write(Paths.get(
         "file6.txt"), lines, StandardCharsets.UTF_8, 
         StandardOpenOption.CREATE, StandardOpenOption.APPEND);
   }
}

java_files.htm

Advertisements