ADVERTISEMENT
ADVERTISEMENT

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

The task is to create a new empty file in 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.*;

Syntax:

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

    //file creation
    file.createNewFile();

    Output:
    true

Java code 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);
    }
  }
}

Output

sample.txt created successfully...

Java Files & Directories Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.