String readLine


描述

所述java.io.LineNumberReader.readLine()方法读取一行文本。

声明

以下是java.io.LineNumberReader.readLine()方法的声明

public String readLine()

参数

NA

返回值

该方法返回一个包含该行内容的字符串,不包括任何行终止字符,如果到达流的末尾,则返回null。

例外

IOException - 如果发生I / O错误。

实例

以下示例显示了java.io.LineNumberReader.readLine()方法的用法。

package com.tutorialspoint;

import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

public class LineNumberReaderDemo {
   public static void main(String[] args) throws IOException {
      FileReader fr = null;
      LineNumberReader lnr = null;
      String str;
      int i;

      try {
         // create new reader
         fr = new FileReader("C:/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();
      }
   }
}

假设我们有一个文本文件c:/test.txt,它具有以下内容。此文件将用作示例程序的输入

ABCDE

让我们编译并运行上面的程序,这将产生以下结果

(1)ABCDE
(2)FGHIJ
(3)KLMNO
(4)PQRST
(5)UVWXY
(6)z