Java.io.LineNumberInputStream.read() 方法



描述

java.io.LineNumberInputStream.read(byte[] b, int off, int len) 方法最多讀取此輸入流中的 len 個位元組到位元組陣列中。此方法會阻塞,直到有輸入可用。

宣告

以下是 java.io.LineNumberInputStream.read(byte[] b, int off, int len) 方法的宣告:

public int read(byte[] b, int off, int len)

引數

  • b − 將資料讀取到的緩衝區。

  • off − 資料的起始偏移量。

  • len − 讀取的位元組最大數量。

返回值

該方法返回讀取到緩衝區中的位元組總數,如果沒有更多資料則返回 -1。

異常

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

示例

以下示例演示了 java.io.LineNumberInputStream.read(byte[] b, int off, int len) 方法的用法。

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;
      byte[] buf = new byte[5];
      int i;
      char c;
      
      try {
         // create new input stream
         fis = new FileInputStream("C:/test.txt");
         lnis = new LineNumberInputStream(fis);
         
         // read bytes to the buffer
         i = lnis.read(buf, 2, 3);
         System.out.println("The number of char read: "+i);
               
         // for each byte in buffer
         for(byte b:buf) {
         
            // if byte is zero
            if(b == 0)
               c = '-';
            else
               c = (char)b;
      
            // print char
            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

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

The number of char read: 3
--ABC
java_io_linenumberinputstream.htm
廣告
© . All rights reserved.