當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java 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.read() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。