java - 将匹配后的所有内容存储在字符串中的数组列表中
问题描述
我有一个方法,它获取一个带有 txt 文件路径作为参数的文件。缓冲读取器将一些行读入数组列表。到目前为止一切都很好,但现在我需要将每个元素存储在字符串中的特定元素之后。
示例:我在这个数组列表中有一个元素,它是'=',在我点击这个元素之后我想把这个元素之后的每个元素都存储到一个字符串中。
我玩过循环和 if 语句,但找不到解决方案。
//Just for debugging purpose at some point i want to store a temperature in here and return it to Main
int temp = 1;
List<String> sensor_Daten = new ArrayList<>();
try
{
BufferedReader reader = new BufferedReader(new FileReader(path));
String line;
while ((line = reader.readLine()) != null)
{
sensor_Daten.add(line);
}
}
catch (IOException IOEx)
{
}
return temp;
解决方案
它不应该太难:
BufferedReader reader = new BufferedReader(new FileReader(path));
String line;
boolean isWordFound = false;
while ((line = reader.readLine()) != null) {
// add the line in the list if the word was found
if (isWordFound()){
sensor_Daten.add(line);
}
// flag isWordFound to true when the match is done the first time
if (!isWordFound && line.matches(myRegex)){
isWordFound = true;
}
}
作为旁注,您不要关闭流,而您应该这样做。该try-with-resource
声明为您做到了这一点。所以你应该赞成这种方式。
概括地说:
BufferedReader reader = ...;
try{
reader = new BufferedReader(new FileReader(path));
}
finally{
try{
reader.close();
}
catch(IOException e) {...}
}
应该只是:
try(BufferedReader reader = new BufferedReader(new FileReader(path))){
...
}
推荐阅读
- python - SQL Server 数据库上的 Python SQL 查询运行速度极慢,同时使用 cursor.execute() 和 read_sql
- javascript - 有没有办法访问缩短的 url 并解析该 url 的扩展版本?R、Python、JS/节点
- visual-studio - Visual Studio 社区 IDE 中是否有代码片段?
- tensorboard - 将 tensorboard 配置为不进行平滑处理——对于某些绘图
- javascript - Node.js 子进程执行返回:错误:kill EPERM STDERR STDOUT_SIZE
- python - Dask Dataframe:选择每小时使用值大于每日平均值的行
- python - Python 不会运行我的项目——有人想检查我的代码吗?
- java - 从命令行创建一个基本的聊天机器人
- python - 规范化/调整时间序列数据框
- typescript - 将泛型类型 T 限制为在 TypeScript 中未定义?