簡體   English   中英

將匹配后的所有內容存儲在String中的Array List中

[英]Store everything after a match in Array List in a String

我有一個方法,它獲取一個文件,其中包含一個txt文件的路徑作為參數。 緩沖讀取器將一些行讀入arraylist。 到目前為止這么好但現在我需要在String中的特定元素之后存儲每個元素。

示例:我在此數組列表中有一個元素,在我點擊此元素之后是'='我想將此元素后面的每個元素存儲到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;

這不應該太難:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM