简体   繁体   English

使用FileReader类从位置Java读取文件

[英]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. 我正在使用FileReader类尝试访问同一目录中的.txt文件。 The only way I've made it work is by using the directory path starting from Users. 我使之起作用的唯一方法是使用从Users开始的目录路径。

Worth noting - I'm using intellij community edition on Mac 值得注意的是-我在Mac上使用的是intellij社区版

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" 仅使用“ 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.. 同样在类似情况下,也可以使用File.getAbsolutePath()来检查文件的确切位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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