Skip to main content

Command Palette

Search for a command to run...

Check if file exists at given path using Java and create if NOT

Published
1 min read

Problem statement : Want to check if a file exists or not at given location and create if not to avoid FileNotFoundexception

Solution : using Java

public void createFileIfDoesNotExists() throws IOException {

File usersHTMLFile = new File(System.getProperty("user.dir") + "/Report.html");
  System.out.println("file Report.html exists : "+usersHTMLFile.exists());

if(!usersHTMLFile.exists())
  {
      System.out.println("creating file Report.html ");
      usersHTMLFile.createNewFile();
      System.out.println("file Report.html exists : "+usersHTMLFile.exists());
  }
}

Explanation :

using File property exists to check if file already present using File createNewFile() to create a file Output when File does not exists in given path

file Report.html exists : false
creating file Report.html 
file Report.html exists : true

Output when File exists in given system path

file Report.html exists : true

W

Nice! I like to use the Files utility class, look:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
  public static void main(String... args) throws IOException {
    final Path path = Paths.get(System.getProperty("user.dir"), "Report.html");

    if (Files.notExists(path))
      Files.createFile(path);
  }
}
1
A
Amit Sahu5y ago

Good approach! this also serves our purpose. Wellington Domiciano

1