I am new to Java and come from a C++ background. I made a really simple code just to test out file reading. I have an input file called "input.txt" and its in the same file as my main file called "Main.java". However, when I try to create a new instance of a File object using the name "input. txt", it does not find the file and file.exists() returns false. When I instead put the full path name, it does find the file. The code is displayed below:
public static void main(String[] args) throws FileNotFoundException
{
// File file = new File("C:/Users/josep/OneDrive/Documents/java/input.txt"); //This works
File file = new File("input.txt"); //why won't this work?
if( file.exists() )
{
System.out.println("File exists");
}
else
{
System.out.println("Doesn't exist"); //this prints out.
}
Scanner input = new Scanner(file);
String str = input.nextLine();
System.out.println("Str: " + str);
input.close();
}
}
Am I doing something wrong here because I do not see why I shouldn't be able to just enter the file name instead of the full path. In C++, if the files were in the same folder I could just enter the file name so I'm confused as to why that is not working here. Below is the output I get:
Doesn't exist
Exception in thread "main" java.io.FileNotFoundException: input.txt (The system cannot find the file specified)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:211)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:153)
at java.base/java.util.Scanner.<init>(Scanner.java:639)
at Main.main(Main.java:22)
Can anyone help me understand what is going on? Any help would be greatly appreciated.