我一直在尝试了解 FileReader
,因此想对其进行测试。我创建了一个类,其构造函数接受一个字符串(文件名)并创建一个文件,然后从中读取并打印出第一个字符,但我的代码无法正常工作并显示错误。这是我的java代码。
package test_3;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Files {
public Files(String s) throws FileNotFoundException, IOException{
File f = new File(s);
FileReader fr = new FileReader(f);
System.out.println(fr.read());
}
public static void main(String args[]) throws FileNotFoundException, IOException{
Files myFile = new Files("input.txt");
}
}
这是错误信息
Exception in thread "main" java.io.FileNotFoundException: input.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at test_3.Files.<init>(Files.java:11)
at test_3.Files.main(Files.java:16)
最佳答案
因为找不到文件。您应该做的是获取 java 查找文件的路径,就像这样。
System.out.print(System.getProperty("user.dir"));
然后将“input.txt”放入该目录(运行该代码时打印的目录)。
或者,使用 input.txt 的完整绝对路径
关于java - 使用 FileReader 的 java 中的这段代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36780387/