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
- a Class called
Main
- 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.