当前位置: 首页 > 文档资料 > 学习 Java 编程 >

ByteArrayInputStream

优质
小牛编辑
115浏览
2023-12-01

ByteArrayInputStream类允许将内存中的缓冲区用作InputStream。 输入源是一个字节数组。

ByteArrayInputStream类提供以下构造函数。

Sr.No.构造函数和描述
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个字节数。 返回读取的总字节数。 如果它是文件的结尾,则返回-1。

3

public int available()

给出可以从此文件输入流中读取的字节数。 返回一个int,它给出了要读取的字节数。

4

public void mark(int read)

这将设置流中当前标记的位置。 该参数给出了在标记位置变为无效之前可以读取的最大字节数限制。

5

public long skip(long n)

从流中跳过'n'个字节。 这将返回跳过的实际字节数。

例子 (Example)

以下是演示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(); 
      }
   }
}

以下是上述计划的样本运行 -

输出 (Output)

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