java - 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();
}
解决方案
这两个 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(); 不应在尝试部分关闭!
祝你好运!
推荐阅读
- r - 在 R 中绘制 native-land.ca json
- java - 如何在 kotlin 中修改或生成代码?(不仅是 JVM)
- google-cloud-platform - 谷歌函数构建失败:发现不兼容的依赖项(Python)
- go - 使用反射确定结构字段是否不完整 Cgo 类型
- reactjs - useMemo 不影响组件渲染
- c++ - 使用所有英特尔编译器时打开 CMake MSVC 变量
- c++ - How to only use some of the optional arguments of a function
- django - 在 Django 中删除表条目
- html - 滚动一个绝对正确的 div
- sql - PL/SQL 使用表变量作为查询表