字节数组流ByteArrayOut(In)putStream使用详解

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: 字节数组流ByteArrayOut(In)putStream使用详解

【1】字节数组流

ByteArrayOutputStream: 可以捕获内存缓冲区的数据,转换成字节数组(toByteArray()方法)。

ByteArrayInputStream: 可以将字节数组转换为输入流。


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

类继承示意图如下:



主要属性和方法如下:



测试示例如下:

  @Test
  public void byteArray() throws IOException{
    ByteArrayOutputStream bout=new ByteArrayOutputStream();
    //只能输入字节,不能输入中文字符
    bout.write(1);  
    bout.write(2); 
    bout.write(3);
    核心方法--获取内存缓冲中的数据--字节数组
    byte[] buf=bout.toByteArray();
    System.out.println(buf.length+","+buf.getClass());
    for(int i=0;i<buf.length;i++)
    {
      System.out.println(buf[i]);
    }
    bout.close();
    System.out.println("输出流结束。。。输入流开始。。。");
    //ByteArrayInputStream: 可以将字节数组转化为输入流
    ByteArrayInputStream bin=new ByteArrayInputStream(buf);
    int data=0;
    while( (data=bin.read())!=-1)
    {
      System.out.println(data);
    }
    bin.close();
  }


result as follows :

3,class [B // 表示Byte数组
1
2
3
输出流结束。。。输入流开始。。。
1
2
3


如果输入英文字符,将会输出其ASCII值:

如a 的ascii为97,i 为105

bout.write('i');  
bout.write(2); 
bout.write(3);


result as follows :

3,class [B
105
2
3
输出流结束。。。输入流开始。。。
105
2
3


【2】与DataOutputStream&DataInputStream联合使用

实例代码如下:

  @Test
  public void testBAOPStream() throws IOException{
    //与DataOutputStream&DataInputStream联合使用:
    ByteArrayOutputStream bout=new ByteArrayOutputStream();
    DataOutputStream dos=new DataOutputStream(bout);
    String name="suntao";
    int age=19;
    dos.writeUTF(name);
    dos.writeInt(age);
    //获取内存缓冲区中的数据
    byte[] buf=bout.toByteArray();
    for(int i=0;i<buf.length;i++)
    {
//      System.out.println((char)buf[i]);
      System.out.println(buf[i]);
    }
    System.out.println(new String(buf));
    System.out.println(new String(buf).trim());
    dos.close();
    bout.close();
    ByteArrayInputStream bin=new ByteArrayInputStream(buf);
    DataInputStream dis=new DataInputStream(bin);
    name=dis.readUTF();//从字节数组中读取,自动进行编码转换
    age=dis.readInt();
    System.out.println("name :"+name+","+"age :"+age);
    dis.close();
    bin.close();
  }


result as follows :

115-s , ,97 - a



【3】与System.in,System.out配合使用

测试示例如下:

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;
      ByteArrayOutputStream bInput = new ByteArrayOutputStream(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(); 
      }
   }
}


result as follows :

adfsdfsfdas
Print the content
a   d   f   s   d   f   s   f   d   a      
Converting characters to Upper case 
A
D
F
S
D
F
S
F
D
A



【4】与ObjectInputStream&ObjectOutputStream联合使用

这里模拟使用Redis的Jedis进行对象的存取。


测试代码示例如下:

public static void setexObj(String key, int seconds, Object obj) throws Exception {
    Jedis jedis = RedisCachedFactory.getJedis();
    jedis.setex(key.getBytes(), seconds, serialize(obj));
    RedisCachedFactory.close(jedis);
  }
public static Object getObj(String key) throws Exception {
  Object obj = null;
  Jedis jedis = RedisCachedFactory.getJedis();
  obj = unserialize(jedis.get(key.getBytes()));
  RedisCachedFactory.close(jedis);
  return obj;
}
//将对象序列化为字节数组
public static byte[] serialize(Object object) throws Exception {
    ObjectOutputStream oos = null;
    ByteArrayOutputStream baos = null;
    try {
      // 序列化
      baos = new ByteArrayOutputStream();
      oos = new ObjectOutputStream(baos);
      oos.writeObject(object);
      //拿到字节数组
      byte[] bytes = baos.toByteArray();
      return bytes;
    } catch (Exception e) {
      throw new Exception(e);
    }
  }
//将字节数组反序列化为对象
public static Object unserialize(byte[] bytes) throws Exception {
  ByteArrayInputStream bais = null;
  try {
    // 反序列化
    bais = new ByteArrayInputStream(bytes);
    ObjectInputStream ois = new ObjectInputStream(bais);
    return ois.readObject();
  } catch (Exception e) {
    throw new Exception(e);
  }
}

关联博文:字节输出流在SpringMVC文件下载中的使用




相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
13天前
|
数据处理 C++
C++程序字符串流
C++程序字符串流
21 2
|
18天前
|
存储 C++
62字符串流
62字符串流
15 0
|
8月前
|
Java
java流是指在Java中用来读写数据的一组有序的数据序列,它可以将数据从一个地方带到另一个地方。java流分为输入流和输出流,输入流是从源读取数据的流,而输出流是将数据写入到目的地的流。Java流又可以分为字节流和字符流,字节流读取的最小单位是一个字节(1byte=8bit),而字符流一次可以读取一个字符(1char = 2byte = 16bit)。Java流还可以分为节点流和处理流,节点流是直接从一个源读写数据的流(这个流没有经过包装和修饰),处理流是在对节点流封装的基础上的一种流。
106 0
|
18天前
|
存储 自然语言处理 Java
day17-缓冲流&转换流&序列化流&打印流&Properties(二)
day17-缓冲流&转换流&序列化流&打印流&Properties
44 1
|
18天前
|
存储
day17-缓冲流&转换流&序列化流&打印流&Properties(一)
day17-缓冲流&转换流&序列化流&打印流&Properties
55 0
|
18天前
day17-缓冲流&转换流&序列化流&打印流&Properties(三)
day17-缓冲流&转换流&序列化流&打印流&Properties
42 1
|
10月前
|
安全 Java
字节数组流和数据流
字节数组流和数据流
48 0
|
18天前
|
存储 Java
对象序列化流和对象反序列化流
对象序列化流和对象反序列化流
48 0
|
10月前
|
存储 Java
字符输入流
字符输入流
46 0
|
10月前
|
SQL JavaScript 前端开发
开始使用流
Java 8 中的 Stream 俗称为流,它与 java.io 包里的 InputStream 和 OutputStream 是完全不同的概念 Stream 用于对集合对象进行各种非常便利、高效的聚合操作,或者大批量数据操作 Stream API 借助于 Lambda 表达式,极大的提高编程效率和程序可读性 同时它提供串行和并行两种模式进行汇聚操作,并发模式能够充分利用多核处理器的优势 通过下面的例子我们可以初步体会到使用 Stream 处理集合的便利性
32 1

热门文章

最新文章