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

·

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