Java ByteArrayInputStream类
ByteArrayInputStream类允许将内存中的缓冲区用作输入流。输入源是一个字节数组。
ByteArrayInputStream类提供了以下构造函数。
| 序号 | 构造函数和描述 | 
|---|---|
| 1 | ByteArrayInputStream(byte [] a) 此构造函数接受一个字节数组作为参数。 | 
| 2 | ByteArrayInputStream(byte [] a, int off, int len) 此构造函数接受一个字节数组和两个整数值作为参数,其中 off 是要读取的第一个字节, len 是要读取的字节数。 | 
一旦你手头有 ByteArrayInputStream 对象,那么就有一系列的辅助方法可以用来读取流或在流上执行其他操作。
| Sr.No. | 方法与描述 | 
|---|---|
| 1 | public int read() 该方法从InputStream中读取下一个字节的数据。返回一个int值作为下一个字节的数据。如果已经到达文件的末尾,则返回-1。 | 
| 2 | public int read(byte[] r, int off, int len) 该方法从输入流中读取起始于off位置的len个字节到数组r中。返回读取的总字节数。如果已经到达文件的末尾,则返回-1。 | 
| 3 | public int available() 给出可以从此文件输入流中读取的字节数。返回一个int值,表示要读取的字节数。 | 
| 4 | public void mark(int read) 在流中设置当前标记位置。参数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
极客教程