【问题标题】:How to read a text file for particular kind of data?如何读取特定类型数据的文本文件?
【发布时间】:2014-12-15 08:44:13
【问题描述】:

我有一个特殊的场景,我试图在两个 while 循环中读取一个文件。在第二个循环中,它从 egining 读取文件,但我想读取第一个 while 停止读取文件的文件。

这是我的代码:

while ((line = br.readLine()) != null) {
    if (line.startsWith(rootId.trim())) {
        break;
    }
}

while (!(line = br.readLine()).contains("---------------------------------------------------")) {
    // my other code stuff 
}

这里我的文件存储数据如下,

-----------------------------------------------------
00001#            // this is the rootId
N1
N2
-----------------------------------------------------
00002#
N1
N2
-----------------------------------------------------
00003#
N1
N2

此方法采用 rootId 并显示 Nodes(N1,N2) 和我的其他内容。在这里,我的策略是读取文件,直到我在另一个循环中得到rootId,直到我得到一行(--------)在做我的事情。但在下一个循环中,它再次从头开始读取文件。如何解决这个问题。有什么可以帮助我的。

【问题讨论】:

  • 这段代码看起来不错。你是在给我们看真实的照片吗?
  • 这两行,即在文件中与在您的代码中,破折号的数量不匹配。
  • @almasshaikh 是的,我将其替换为 contains("-------")
  • 正如@ScaryWombat 所说,除了我上面的评论之外,看起来没什么问题。因此,如果这是真正的代码,它应该可以工作。
  • @ScaryWombat 第二个while循环再次开始读取frm。

标签: java file while-loop bufferedreader


【解决方案1】:
    while ((line = br.readLine()) != null) 
    {
        if(line.startsWith(rootId.trim()))
        {
               break;
        }

        if(!(line = br.readLine()).contains("---------------------------------------------------")) 
        {

            // my other code stuff 


        }

    }

你的所有代码都应该在一个循环中,像这样尝试它应该可以工作。

【讨论】:

    【解决方案2】:

    我认为您不需要两个循环 - 您应该能够使用第一个循环然后使用 if- 语句逐行处理您的文件

    while ((line = br.readLine()) != null) 
        {
            if(line.startsWith(rootId.trim())||(line.contains("----"))
            {
                   continue;
            }
            //Process your nodes here - add more if statements if necessary
        }
    

    注意你需要

    continue;
    

    而不是

    break;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-25
      • 2020-07-01
      • 1970-01-01
      相关资源
      最近更新 更多