How to check if a file exists in Java?

To check if a file exists in Java, call the File.exists method.

For example, this is how you can print it exists! if there is an image.png file in the /Users/whaadev directory:

File file = new File("/Users/whaadev/image.png");

if (file.exists()) {
  System.out.println("it exists!");
}