The file can't be found and I don't have to specify the file location because it's in the same directory as the class Test.
The code :
File myFile = new File("aaa.txt");
boolean isExisting = myFile.exists();
System.out.println(isExisting);
try {
FileReader f = new FileReader(myFile);
BufferedReader bf = new BufferedReader(f);
String line = bf.readLine();
while (line != null) {
System.out.println(line);
line = bf.readLine();
}
bf.close();
} catch (FileNotFoundException e) {
System.out.println("Can't find file");
// e.printStackTrace();
} catch (IOException e) {
System.out.println("Error");
}
The error (if not catched) :
java.io.FileNotFoundException: aaa.txt (The specified file cannot be found)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:216)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at java.base/java.io.FileReader.<init>(FileReader.java:75)
at Testing/Packageeee.Test.main(Test.java:29)
They're all in the same directory
You are almost certainly running from the root of your project. Not from the same directory as your text file.
Assuming that aaa.txt
is in a directory called src
the following snippet should work:
String baseDirectory;
try {
baseDirectory = new File("./src").getCanonicalPath();
} catch (IOException e) {
throw new RuntimeException(e);
}
File myFile = new File(baseDirectory, "aaa.txt");