java - Java,文本文件到字符串
问题描述
我正在尝试阅读某些文本文件,当我找到某个单词时,我应该做另一个标准,
在我的代码中(将遵循),我收到一个错误,“类型不匹配:无法从 int 转换为字符串”所以,Eclipse 建议的解决方案是使变量(键)整数而不是字符串这里有什么问题?
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class JNAL {
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("C:/20180918.jrn");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
System.out.println("Total file size to read (in bytes) : "
+ fis.available());
int content;
String key;
/*
while ((content = fis.read()) != -1) {
// convert to char and display it
System.out.print((char) content);
}
*/
while ((key = fis.read()) == "Cash") {
// convert to char and display it
System.out.print((String) key);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
解决方案
您在此代码中有多个问题,但只是为了解决您的问题:
(key = fis.read()) == "Cash"
“现金”是类型String
。您不能将 "primitive"int
与 "Object"进行比较String
,因此 eclipse 建议将原语更改int
为 Object type String
。
关键是,即使这样还不够。在比较不应该使用的对象时,请==
使用equals
.
推荐阅读
- css - 如何在 tinymce 编辑器中更改内置工具栏图标的颜色(v 5.1.2)
- java - 尽管我有管理员权限,但 Spring Boot 返回 403
- python - 如何在 macOS 中使用 python 附加文件夹中存在的多个 .dmg 文件
- python - 访问熊猫列内的列表项
- azure-api-management - 如何将值从请求复制到 Azure API 管理策略中的响应
- flutter - 搜索大写和小写字母的 sembast 数据
- sql - 带有 <> 标记的 SQL 会产生问题。寻找替代代码/方式
- python - 使用 beautifulSoup 下载 html 代码
- c++ - 处理影响跨不同线程共享的对象的定时回调的最佳方法是什么?
- php - HTML 有条件的脑洞 (if else)