Java - ByteArrayInputStream read() 方法



描述

Java ByteArrayInputStream read() 方法返回從該輸入流中剩餘可讀取的位元組數。它將值作為 int 返回,範圍為 0 到 255。如果由於到達流的末尾而沒有可用的位元組,則返回 -1。此 read 方法不會阻塞。

宣告

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

public int read()

引數

返回值

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

異常

示例 1

以下示例演示了 Java ByteArrayInputStream read() 方法的使用。我們建立了一個名為 buf 的 byte[] 變數,並初始化了一些位元組。我們建立了一個 ByteArrayInputStream 引用,然後用 buf 變數對其進行初始化。在 while 迴圈中,我們使用 read() 方法將流讀取到一個 int 中,然後透過將其轉換為 char 來列印其值。

import java.io.ByteArrayInputStream;
import java.io.IOException;
public class ByteStreamTest {
   public static void main(String[] args) throws IOException {
      byte[] buf = {65, 66, 67, 68, 69};
      ByteArrayInputStream bais = null;
      
      try {
         // create new byte array input stream
         bais = new ByteArrayInputStream(buf);
         
         int b =0;
         
         // read till the end of the stream
         while((b = bais.read())!=-1) {
            
            // convert byte to character
            char c = (char)b;
            
            // print
            System.out.println("byte :"+b+"; char : "+ c);
            
         }
         System.out.print(bais.read()+" Reached the end");
         
      } catch(Exception e) {
         // if I/O error occurs
         e.printStackTrace();
      } finally {
         if(bais!=null)
            bais.close();
      }
   }
}

輸出

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

byte :65; char : A
byte :66; char : B
byte :67; char : C
byte :68; char : D
byte :69; char : E
-1 Reached the end

示例 2

以下示例演示了 Java ByteArrayInputStream read() 方法的使用。我們建立了一個名為 buf 的 byte[] 變數,並用空陣列對其進行初始化。我們建立了一個 ByteArrayInputStream 引用,然後用 buf 變數對其進行初始化。在 if 迴圈中,我們使用 read() 方法檢查流是否包含任何位元組,然後列印其結果。

import java.io.ByteArrayInputStream;
import java.io.IOException;
public class ByteStreamTest {
   public static void main(String[] args) throws IOException {
      byte[] buf = {};
      ByteArrayInputStream bais = null;
      
      try {
         // create new byte array input stream
         bais = new ByteArrayInputStream(buf);
         
         int b =0;
         
         // read the stream
         if((b = bais.read())!=-1) {
            // convert byte to character
            char c = (char)b;
            
            // print
            System.out.println("byte :"+b+"; char : "+ c);
         }else{
            System.out.print("byte stream is empty");
         } 
      } catch(Exception e) {
         // if I/O error occurs
         e.printStackTrace();
      } finally {
         if(bais!=null)
            bais.close();
      }
   }
}

輸出

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

byte stream is empty
java_bytearrayinputstream.htm
廣告

© . All rights reserved.