Tucker Beauchamp Tucker Beauchamp - 5 months ago 29
Java Question

Use FileReader Class to read file from location Java

I'm using the FileReader class to try and access a .txt file in the same directory. The only way I've made it work is by using the directory path starting from Users.

Worth noting - I'm using intellij community edition on Mac


Scanner inFile = new Scanner(new FileReader("/Users/tuckerbeauchamp/Desktop/Java-Class/Famous Scientist/src/com/names.txt"));

error I get when using just "names.txt"

Exception in thread "main" java.io.FileNotFoundException: names.txt (No such file or directory)
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.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at com.FamousCS.main(FamousCS.java:25)
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:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)



If you have the text file in the same directory as your source file(s), the text file will be available in the class path when you run the program. So you can access the file using the Class loader:

InputStream stream = FamousCS.class.getClassLoader().getResourceAsStream("/com/names.txt");
Scanner scanner = new Scanner(stream);