Search code examples
javaintellij-ideaiorelative-pathfile-exists

.exist() - file does not exist, when using relative path


Edit: If you have landed on this question, chances are you are unfamiliar with the concept - working directory.

I don't know if this is specific to IntelliJ IDEA's current working directory or I do not understand the concept of relative files well enough. I did come to a conclusion that solves my problem, but it leaves a lot of things unanswered for me, I don't like to just memorize stuff, I want to understand it. That is why I am asking this question here, thank you in advance.

Let's say you have

  1. a Class called Main
  2. a text file called text1.txt

and they are both located in the folder src

In the Main class you have written the following code

public class Main {

    public static void main(String[] args) {        
        // Scanner
        Scanner scanner = new Scanner(System.in);       
        // File object
        File myFile = new File("text1.txt");
        // Prints a String, that tells you if the file exists
        System.out.println("File exists = " + myFile.exists());
    }

}

Result: File exists = false

Why does this happen?

The question has received a good answer already, however, if you find this is not enough for you, then read the article below, it goes more in-depth.

https://www.earthdatascience.org/courses/intro-to-earth-data-science/python-code-fundamentals/work-with-files-directories-paths-in-python/


Solution

  • An absolute path starts from the filesystem root. Compare it to an address on a letter. The postman knows where to deliver that letter.

    A relative path is not a target address. It is more like - when you see the gas station, turn left. Depending from which direction you come, you end up in various other locations.

    Back to computers: relative paths are calculated based on a current working directory. You can print that from your java program by checking

    How to get the current working directory in Java?

    I usually write my code to be a bit clearer about the events. The following code will not only tell whether it found the file but also let you know where exactly it was searching for it.

            // File object
            File myFile = new File("text1.txt");
    
            // Prints a String, that tells you if the file exists
            System.out.println("File "+myFile.getAbsolutePath()+" exists = " + myFile.exists());