为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

ITMISS 2022-12-28 16:38:43
我有一个方法,它获取一个文件,其中包含一个 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;
查看完整描述

1 回答

?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

它不应该太难:


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

    ...

}


查看完整回答
反对 回复 2022-12-28
  • 1 回答
  • 0 关注
  • 105 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号