首页 > 解决方案 > FileInputStream 无法转换为 Reader

问题描述

我正在尝试读取我的文本文件“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();
    }

标签: javanetbeansjflex

解决方案


这两个 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 的示例:如何在 Java 中使用 Buffered Reader

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

祝你好运!


推荐阅读