java - 如何编写在文本文件中搜索字符串并在其后返回 int 值的方法?
问题描述
我需要的是在文本文件中搜索特定字符串并在此字符串之后返回 int 值的 Java 方法。如何将读取的行与文本文件分开。我的文本文件如下所示:
namea 80
nameb 50
namec 200
named 3400
文本文件应该有更多的行。
我的方法现在看起来像这样:
public int readfile(String searchedString, File txtfile){
int ret = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(txtfile));
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith(searchedString + " ")) {
ret = Integer.parseInt(//the number of the line);
}
}
br.close();
System.out.println(ret);
} catch (IOException ex) {
}
return ret;
}
解决方案
public int readfile(String searchedString, File txtfile){
int ret = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(txtfile));
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith(searchedString + " ")) {
String[] strArr = line.split(" ");
int item = strArr.length - 1;
ret = Integer.parseInt(strArr[item]);
}
}
br.close();
System.out.println(ret);
} catch (IOException ex) {
//handle it
}
return ret;
}
推荐阅读
- android-studio - 我的 Ionic 应用程序无法从 Android 模拟器访问我的本地节点服务器
- c - 释放从核心中排除的内存后核心转储大小增加
- java - 将队列变成优先队列
- android - ViewBinding - 如何动态切换/选择布局(
)? - html - 如何将 ul 列表作为按钮对齐到中心
- java - Firebase 和 Play Core onCompleteListener 不兼容的类型
- vue.js - 为什么在我的模板中反应性属性不是反应性的?
- docker - 将 docker 资源分离到不同的命名空间中
- mysql - MySQL 中的 DATEDIFF
- flutter - 从另一个列表中的值创建新列表