将匹配后的所有内容存储在字符串的数组列表中

时间:2019-06-03 17:37:50

标签: java

我有一个方法,该方法获取带有txt文件路径的文件作为参数。缓冲的读取器将一些行读取到arraylist中。到目前为止还不错,但是现在我需要将每个特定元素之后的每个元素存储在String中。

示例:我在此数组列表中有一个元素,当我点击该元素后,该元素为'=',我想将该元素之后的每个元素存储到字符串中。

我玩过循环和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;

1 个答案:

答案 0 :(得分:0)

应该不太难:

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