Java Programs

Java Practice

Create a new empty file in Java

Java empty file creation: Here, we are going to learn how to create a new empty file java?
Submitted by IncludeHelp, on July 18, 2019

Problem statement

The task is to create a new empty file in Java.

Java - Creating a new empty file

To create a new empty file in java – we use createNewFile() method of "File" class. The createNewFile() method is called with the File object which should be initialized with the file name (and path if you want to specify).

The createNewFile() method returns a Boolean value if file created successfully it returns "true" otherwise it returns "false".

Package to use: import java.io.*;


//file object creation
File file = new File("D://sample.txt");

//file creation


Java program to create a new empty file

//Java code to create a new empty file

import java.io.*;

public class Main {
  public static void main(String[] args) {
    //creating file object
    File file = new File("sample.txt");

    //following syntax can be used to define 
    //path (D://sample.txt) also
    //File file = new File("D://sample.txt");

    //variable to store result
    //'true' - file created successfully
    //'false' - file is not created successfully
    boolean result = false;

    try {
      result = file.createNewFile();
      System.out.println(file.getPath() + " created successfully...");
    } catch (IOException exp) {
      System.out.println("Error while creating file: " + exp);


sample.txt created successfully...

Java Files & Directories Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.