【问题标题】:FileInputStream cannot be converted to ReaderFileInputStream 无法转换为 Reader
【发布时间】:2019-01-17 20:05:05
【问题描述】:

我正在尝试读取我的文本文件“inputFile.txt”,但系统显示以下错误。 谁能帮我解决这个错误?谢谢!

错误:不兼容的类型:FileInputStream 无法转换为 Reader Yylex yy = new Yylex(fin);

    //create file object
    File infile = new
    File("C://name//test_jflex//inputFile.txt");
    int ch;
    StringBuffer strContent = new StringBuffer("");
    FileInputStream fin = null;
    try {
        fin = new FileInputStream(infile);
        Yylex yy = new Yylex(fin);
        Yytoken t;
        while ( (t = yy.yylex()) != null )
            System.out.println(t);
        fin.close();
    }

【问题讨论】:

  • new Yylex(new BufferedReader(fin)); 或直接new Yylex(new FileReader(infile))

标签: java netbeans jflex


【解决方案1】:

这两个 java.io.Reader 和 java.io.FileInputStream 不兼容。这是因为 FileInputStream 使用字节,而 Reader 是字符流的接口。如果你去https://docs.oracle.com/javase/8/docs/api/java/io/FileInputStream.html 你会看到FileInputStream 没有实现Reader。这就是为什么您需要选择使用 Reader + 他的实现类或使用 FileInputStream。

FileInputStream 示例:https://www.mkyong.com/java/how-to-read-file-in-java-fileinputstream/

Reader 的一种实现 java.io.BufferedReader 的示例:How to use Buffered Reader in Java

附:请适当关闭所有流。你的 fin.close();不应在试用部分关闭!

祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    • 2015-02-11
    • 2015-07-20
    • 1970-01-01
    相关资源
    最近更新 更多