java 中使用 FileReader 的这段代码有什么问题?

What's wrong with this code in java that uses FileReader?

我一直在尝试了解 FileReader,因此想对其进行测试。我创建了一个 class ,其构造函数接受一个字符串(文件名)并创建一个文件,然后从中读取并打印出第一个字符,但我的代码无法正常工作并显示错误。这是我的 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

的完整绝对路径