How do I check if a file exists in Java?

To check if a file exists in Java, you can use the exists method of the File class from the java.io package. This method returns true if the file exists, and false if it doesn't. Here's an example of how you can use this method:

import java.io.File;

public class Main {
  public static void main(String[] args) {
    // Set the file path
    String filePath = "C:\\folder\\file.txt";

    // Create a File object
    File file = new File(filePath);

    // Check if the file exists
    if (file.exists()) {
      System.out.println("File exists");
    } else {
      System.out.println("File does not exist");
    }
  }
}

This code will check if the file at the specified file path exists, and print the appropriate message to the console.

Note that the exists method only checks for the existence of the file on the file system. It does not guarantee that the file can be read or written, or that it is a regular file (as opposed to a directory or a symbolic link, for example). To perform these checks, you can use other methods of the File class, such as isFile, canRead, and canWrite.