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

标签 java file-io filereader

我一直在尝试了解 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/

相关文章:

java - 使用 rome 遍历 feed 条目

c++ - 逐字逐句阅读长文本

javascript - 无法循环或映射到 FileReader blob

javascript - 如何在 JavaScript 中逐字节循环文件?

java - 基于 JPA Criteria 的查询,一次与三个查询相交

java - selenium 2.0 中的 isElementPresent

java - 为 jvm 使用所有可用的系统内存

c - 如何使用 fwrite() 将无符号长整数值写入文本文件?

java - 删除共享文件spring MVC

java - Java中如何查找某个单词在哪一行