15.1 ByteArrayInputStream(字节数组输入流)和ByteArrayOutputStream类(字节数组输出流)

字节数组流对象

字节数组流对象分为输入流和输出流。分别是:ByteArrayInputStream和ByteArrayOutputStream。

ByteArrayInputStream类

字节数组输入流在内存创建一个字节数组缓冲区,从输入流读取的数据保存在该字节数组缓冲区中。创建字节数组输入流对象有以下方式:

//方法 1
ByteArrayInputStream bArray = new ByteArrayInputStream(byte [] a);
//方法 2
ByteArrayInputStream bArray = new ByteArrayInputStream(byte []a, int off, int len)

字节数组流对象的方法:

序号方法及描述
1public int read()
从此输入流中读取下一个数据字节。
2public int read(byte[] r, int off, int len)
将最多 len 个数据字节从此输入流读入字节数组。
3public int available()
返回可不发生阻塞地从此输入流读取的字节数。
4public void mark(int read)
设置流中的当前标记位置。
5public long skip(long n)
从此输入流中跳过 n 个输入字节。

ByteArrayOutputStream类

字节数组输出流在内存中创建一个字节数组缓冲区,所有发送到输出流的数据保存在该字节数组缓冲区中。
创建方式:

//方法 1
OutputStream bOut = new ByteArrayOutputStream();
//方法 2
OutputStream bOut = new ByteArrayOutputStream(int a);

字节数组输出流对象的方法:

序号方法及描述
1public void reset()
将此字节数组输出流的 count 字段重置为零,从而丢弃输出流中目前已累积的所有数据输出。
2public byte[] toByteArray()
创建一个新分配的字节数组。数组的大小和当前输出流的大小,内容是当前输出流的拷贝。
3public String toString()
将缓冲区的内容转换为字符串,根据平台的默认字符编码将字节转换成字符。
4public void write(int w)
将指定的字节写入此字节数组输出流。
5public void write(byte []b, int off, int len)
将指定字节数组中从偏移量 off 开始的 len 个字节写入此字节数组输出流。
6public void writeTo(OutputStream outSt)
将此字节数组输出流的全部内容写入到指定的输出流参数中。



下面是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 ) {
             // 获取用户输入
             bOutput.write(System.in.read()); 
          }
          byte b [] = bOutput.toByteArray();
          System.out.println("Print the content");
          for(int x= 0 ; x < b.length; x++) {
             // 打印字符
             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(); 
          }
       }
}

结果为:

jikhuygftrde
Print the content
j   i   k   h   u   y   g   f   t   r      
Converting characters to Upper case 
J
I
K
H
U
Y
G
F
T
R

注意:只能输入10个字符。不能少,多的部分会忽略。


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值