Java - File Create by File Object

Introduction

You can create a new file using the createNewFile() method of the File class:

Create a File object to represent the abstract pathname

File myFile = new File("dummy.txt");
// Create the file
boolean fileCreated = myFile.createNewFile();

The createNewFile() method creates a new, empty file if the file does not already exist.

It returns true if the file is created successfully; otherwise, it returns false.

The method throws an IOException if an I/O error occurs.

Demo

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

public class Main {
  public static void main(String[] args) {
    File myFile = new File("dummy.txt");
    // Create the file
    try {/*from  w w w . j a v  a 2 s  . co  m*/
      boolean fileCreated = myFile.createNewFile();
      System.out.println(fileCreated);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Result

Related Topic