My objective is to read a text file on IntelliJ. However, when I ran my codes, I get a "FileNotFoundException" message. My file exists. I triple-checked to make sure that the path is correct. I've scoured Stack Overflow looking for an answer, read every question I've come across, but no one offered a concrete solution to the issue.
This is my code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class LetterGrader {
public static void main(String[] args) {
String curDir = new File(".").getAbsolutePath();
System.out.println("Current sys dir: " + curDir);
try {
File inputData = new File("input.txt");
BufferedReader br = new BufferedReader(new FileReader(inputData));
} catch (IOException e) {
System.out.println("File not found");
e.printStackTrace();
}
}
}
This is the error message that showed up.
File not found
java.io.FileNotFoundException: input.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileReader.<init>(FileReader.java:72)
at LetterGrader.main(LetterGrader.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Process finished with exit code 0
Any help would be greatly appreciated! When I find a solution, I will respond back, too.
[UPDATE]
I solved the issue by moving my "input.txt" file out or src folder and into the main project's folder.
I also used Scanner instead of BufferedReader.
My final code that worked:
try {
Scanner diskScanner = new Scanner(new File("input.txt"));
while (diskScanner.hasNextLine()) {
System.out.println(diskScanner.nextLine());
}
diskScanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
inputData
doesn't point to the file you think it points to. Try with absolute path or simply try to print the absolute path ofinputData
and look what the output is. – GallagherSystem.getProperty("user.dir");
and see if the directory is the one where the file is. If not, usegetAbsolutePath()
– Benzedrine