首页 > 解决方案 > 将匹配后的所有内容存储在字符串中的数组列表中

问题描述

我有一个方法,它获取一个带有 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;

标签: java

解决方案


它不应该太难:

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))){
    ...
}

推荐阅读