Java 教程

Java 控制語句

面向物件程式設計

Java 內建類

Java 檔案處理

Java 錯誤和異常

Java 多執行緒

Java 同步

Java 網路

Java 集合

Java 介面

Java 資料結構

Java 集合演算法

高階 Java

Java 雜項

Java API 和框架

Java 類參考

Java 有用資源

Java - 位元組陣列輸入流



ByteArrayInputStream 類允許將記憶體中的緩衝區用作 InputStream。輸入源是位元組陣列。

ByteArrayInputStream 類提供以下建構函式。

序號 建構函式和描述
1

ByteArrayInputStream(byte [] a)

此建構函式接受位元組陣列作為引數。

2

ByteArrayInputStream(byte [] a, int off, int len)

此建構函式採用位元組陣列和兩個整數值,其中off 是要讀取的第一個位元組,len 是要讀取的位元組數。

一旦您擁有 ByteArrayInputStream 物件,則有一系列輔助方法可用於讀取流或對流執行其他操作。

序號 方法和描述
1

public int read()

此方法從 InputStream 讀取下一個資料位元組。返回一個 int 作為下一個資料位元組。如果它是檔案末尾,則返回 -1。

2

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

此方法從輸入流中讀取最多len 個位元組,從off 開始,寫入陣列中。返回讀取的位元組總數。如果它是檔案末尾,將返回 -1。

3

public int available()

給出可以從此檔案輸入流讀取的位元組數。返回一個 int,表示要讀取的位元組數。

4

public void mark(int read)

這將設定流中當前的標記位置。引數給出在標記位置失效之前可以讀取的位元組的最大限制。

5

public long skip(long n)

跳過流中的 'n' 個位元組。這將返回實際跳過的位元組數。

示例

以下示例演示了 ByteArrayInputStream 和 ByteArrayOutputStream。

import java.io.*;
public class ByteStreamTest {

   public static void main(String args[])throws IOException {
      ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);

      while( bOutput.size()!= 10 ) {
         // Gets the inputs from the user
         bOutput.write("hello".getBytes()); 
      }
      byte b [] = bOutput.toByteArray();
      System.out.println("Print the content");
      
      for(int x = 0 ; x < b.length; x++) {
         // printing the characters
         System.out.print((char)b[x]  + "   "); 
      }
      System.out.println("   ");
      
      int c;
      ByteArrayInputStream bInput = new ByteArrayInputStream(b);
      System.out.println("Converting characters to Upper case " );
      
      for(int y = 0 ; y < 1; y++) {
         while(( c = bInput.read())!= -1) {
            System.out.println(Character.toUpperCase((char)c));
         }
         bInput.reset(); 
      }
   }
}

以下是上述程式的示例執行結果:

輸出

Print the content
h   e   l   l   o   h   e   l   l   o      
Converting characters to Upper case 
H
E
L
L
O
H
E
L
L
O
java_files_io.htm
廣告