File Exists() method finds file that does not exist in Eclipse Java Package

Tags: , ,



Please see my code below. I’m working in Eclipse. The project I’m working on definitely does not have an attached file called “log.txt”. But when I run the code below, the value “Exists” is printed to the console. What could be driving this?

        File f = new File("log.txt");
        if(f.exists()) {    
            System.out.println("Exists");
        } else {
            System.out.println(" Doesnt Exist");
        }

Answer

Relative paths such as “log.txt” are resolved against the user’s “current working directory” which depends on how the application is started. The application could be looking for log.txt anywhere on the file system.

If .exists returns true, the file exists. Print the absolute file path to see where the file is located:

System.out.println(f.getAbsoluteFile() + " Exists");


Source: stackoverflow