Hello, I'm new to Java and I come from a C/C++ background. I'm having an issue reading in a file using the Scanner class. I keep getting the FileNotFoundException and I have no idea what I am doing wrong. input.txt is in the same folder as Main.java yet the Scanner still throws the exception. My code is displayed below:
import java.io.File;
import java.nio.file.Path;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
File file = new File("C:/Users/josep/OneDrive/Documents/java/input.txt/");
if( file.exists() )
{
System.out.println("File exists");
}
else
{
System.out.println("Doesn't exist");
}
Scanner input = new Scanner(file);
}
}
I used file.exists() to see if the file exists and it returns true. If file.exists() returns true, I don't understand how Scanner is unable to find the file. I 've tried a bunch of stuff to try and fix it but nothing I've tried works. Whenever I run it, I get the output below:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type FileNotFoundException
at Main.main(Main.java:21)
Does anyone have any idea what could be the issue? Any help would be greatly appreciated.
________________________________________________________________________________________________________
Also, why do I have to specify the path instead of just putting "input.txt" as in:
File file = new File("C:/Users/josep/OneDrive/Documents/java/input.txt/");
File file = new File("input.txt");
when I try the second one (new File("input.txt")), file.exists() returns false. I don't understand why this is since input.txt is in the same folder as Main.java. In C++ you'd only have to put the file name if the .cpp file and the input file are in the same folder, so I don't understand why that is not the case in Java, or am I doing something wrong (I probably am doing something wrong)?
What I have tried:
The above code is mostly what I have tried. Anything else I tried were more of random trial and error.