简体   繁体   中英

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

code

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);

If the file is in the same directory as the class, simply putting

Scanner inFile = new Scanner(new FileReader("names.txt"));

will also work. No need to load files through class loaders and all.

Also in similar situations, also use File.getAbsolutePath() to check where exactly the file is being looked upon..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM