簡體   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