【问题标题】:Make FileReader read every fourth line with a loop使用循环使 FileReader 每隔四行读取一次
【发布时间】:2012-03-06 18:28:05
【问题描述】:

我的问题是我必须安排,在搜索客户时,安排 while 循环只检查每读取的第四行。

这是我在这个问题上已有的代码:

BufferedReader br = new BufferedReader(new FileReader("Customers.txt"));
String line;

while ((line = br.readLine()) != null)
{
    ...
}

br.close();

有人知道“...”的位置需要什么吗?

谢谢!

【问题讨论】:

    标签: java loops while-loop bufferedreader


    【解决方案1】:

    类似的东西

    int i = 0;
    while ((line = br.readLine()) != null)
    {
       i++;
       if (i % 4 == 0)
       {
          // if i is divisible by 4, then
          // your actual code will get executed
          ...
       }
    
    }
    

    【讨论】:

      【解决方案2】:

      只需在循环结束时调用 br.readLine() 3 次,丢弃输出:

      BufferedReader br = new BufferedReader(new FileReader("Customers.txt"));
      String line;
      
      while ((line = br.readLine()) != null)
      {
          ...
          for(int i=0;i<3;i++){ br.readLine(); }
      }
      
      br.close();
      

      【讨论】:

      • 我认为您的解决方案比我的解决方案更好(即更便宜),我的解决方案使用计数器算术检查每 4 次迭代。
      • @J.D.好的,但是你能告诉我如何在我的代码中得到它,因为我不知道:p
      • 所以现在我可以丢失“...”,它会读取第四行?你也知道这个问题的答案吗?link
      • 我认为br.readLine(); br.readLine(); br.readLine(); 比循环更有效,但无论如何任何编译器都会展开它。
      【解决方案3】:
      BufferedReader br = new BufferedReader(new FileReader("Customers.txt"));
      String line;
      int count 0;
      while ((line = br.readLine()) != null)
      {
          if (count!=3)
              count++;
          else {
              // Do something?
              count=0;
          }
      
      }
      
      br.close();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-08
        • 2020-06-16
        • 1970-01-01
        • 1970-01-01
        • 2021-08-22
        相关资源
        最近更新 更多