繁体   English   中英

使用Java的文件中的特定行

[英]Specific line from file using java

我想从文件中打印特定的行,例如第四行或第二行。 这是我的代码,它仅显示所有行和每个行号。 很抱歉,这是一个简单而愚蠢的问题,但在此先感谢您:D。

FileReader fr = null;
      LineNumberReader lnr = null;
      String str;
      int i;

      try{
         // create new reader
         fr = new FileReader("test.txt");
         lnr = new LineNumberReader(fr);

         // read lines till the end of the stream
         while((str=lnr.readLine())!=null)
         {

            i=lnr.getLineNumber();
            System.out.print("("+i+")");

            // prints string
            System.out.println(str);
             }

      }catch(Exception e){

         // if any error occurs
         e.printStackTrace();
      }finally{

         // closes the stream and releases system resources
         if(fr!=null)
            fr.close();
         if(lnr!=null)
            lnr.close();
      }
   }
}

最简单的方法是简单地跟踪您正在阅读的行。 看来您想使用i 不要忘了break了循环的,一旦你读过你想要的行。

另外,continue语句表示“跳过其他所有内容并转到下一个迭代”。

请参见while和do-while语句

     while((str=lnr.readLine())!=null)
     {
        i=lnr.getLineNumber();
        if(i != 57) continue;
        System.out.print("("+i+")");

        // prints string
        System.out.println(str);
        break;
     }

请记住,如下面的评论所述,LineNumberReader从0开始读取。 因此,这实际上将以自然顺序返回第56行。 如果要自然排序为57,则可以改用此条件语句。 if(i <= 57) continue;

怎么样

if(i == 2){
    System.out.println(str);
    break;
}

您可以输入2而不是2作为命令行参数或用户输入。

在循环内放置一些计数器,并在while循环中添加其他条件,例如counter <4。

这个怎么样。

public static void main(String[] args) 
{
    int lineNo = 2;     // Sample line number
    System.out.println("content present in the given line no "+lineNo+" --> "+getLineContents(lineNo));
}

public static String getContents(int line_no) {

     String line = null;

      try(LineNumberReader  lineNumberReader = new LineNumberReader(new FileReader("path\\to\\file")))
      {
        while ((line = lineNumberReader.readLine()) != null) {
            if (lineNumberReader.getLineNumber() == line_no)  {  
                break;
            }
        }                       
      }
      catch(Exception exception){
          System.out.println("Exception :: "+exception.getMessage());
      }
      finally{
          return line;
      }
}

借助try-with-resources语句,您可以避免显式关闭流,一切由它们来照顾。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM