How to Create a File in Java


In this example we will show the method to create a file in Java.

Source Code

package com.beginner.examples;

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

public class CreateAFile {
  public static void main(String[] args) {
    try {  
      File f = new File("test.txt");
      if (!f.exists()) { // judge whether the file exists
        f.createNewFile(); // create a file
        System.out.println("OK");
      } else {
        System.out.println("File already exists.");
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Output:

OK

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments