Java.io.LineNumberInputStream.read() 方法



描述

java.io.LineNumberInputStream.read() 方法讀取此輸入流中的下一個資料位元組。位元組值以 0 到 255 範圍內的 int 返回。如果已到達流的末尾,則該方法返回 -1。

宣告

以下是 java.io.LineNumberInputStream.read() 方法的宣告:

public int read()

引數

返回值

該方法返回下一個資料位元組,如果到達此流的末尾,則返回 -1。

異常

IOException - 如果發生 I/O 錯誤。

示例

以下示例演示了 java.io.LineNumberInputStream.read() 方法的使用。

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.LineNumberInputStream;

public class LineNumberInputStreamDemo {
   public static void main(String[] args) throws IOException {
      LineNumberInputStream lnis = null;
      FileInputStream fis =null;
      int i;
      char c;
      
      try {
         // create new input stream
         fis = new FileInputStream("C:/test.txt");
         lnis = new LineNumberInputStream(fis);
         
         // read till the end of the file
         while((i = lnis.read())!=-1) {
         
            // converts int to char
            c = (char)i;
            
            // prints
            System.out.print(c);
         }
         
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      } finally {
         // closes the stream and releases any system resources
         if(fis!=null)
            fis.close();
         if(lnis!=null)
            lnis.close();      
      }
   }
}

假設我們有一個文字檔案 c:/test.txt,其內容如下。此檔案將用作我們示例程式的輸入:

ABCDE
FGHIJ
KLMNO
PQRST
UVWXY
z

讓我們編譯並執行上述程式,這將產生以下結果:

ABCDE
FGHIJ
KLMNO
PQRST
UVWXY
z
java_io_linenumberinputstream.htm
廣告

© . All rights reserved.