Q:

Create a new empty file in Java

belongs to collection: Java Files & Directories Programs

0

Package to use: import java.io.*;

Syntax:

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

    //file creation
    file.createNewFile();

    Output:
    true

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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...

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Create a temporary file in Java... >>