我正在使用 FileReader 类尝试访问同一目录中的 .txt 文件。我使其工作的唯一方法是使用从 Users 开始的目录路径。
值得注意 - 我在 Mac 上使用 intellij 社区版
代码
Scanner inFile = new Scanner(new FileReader("/Users/tuckerbeauchamp/Desktop/Java-Class/Famous Scientist/src/com/names.txt"));
仅使用“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)
最佳答案
如果文本文件与源文件位于同一目录中,则运行程序时该文本文件将在类路径中可用。因此您可以使用类加载器访问该文件:
InputStream stream = FamousCS.class.getClassLoader().getResourceAsStream("/com/names.txt");
Scanner scanner = new Scanner(stream);
关于java - 使用 FileReader 类从 Java 位置读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40254907/