ByteArrayOutputStream(字节数组输出流) 示例

本文演示了如何使用Java的ByteArrayOutputStream类来操作字节数组。具体包括将字符串转换为字节数组并写入ByteArrayOutputStream,从该流中读取数据到字节数组,打印数据,将数据写入文件,以及重置流并追加新数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//Demonstrate ByteArrayOutputStream.
import java.io.*;
class ByteArrayOutputStreamDemo{
 public static void main(String[] args) throws IOException{
  ByteArrayOutputStream f = new ByteArrayOutputStream();
  String s = "This should end up in the array";
  byte buf[] = s.getBytes();

  f.write(buf);
  System.out.println("Buffer as a string");
  System.out.println(f.toString());
  System.out.println("Into array");
  byte b[] = f.toByteArray();
  for(int i=0;i<b.length;i++){
   System.out.print((char)b[i]);
  }
  System.out.println("/nTo an OutputStream()");
  OutputStream f2 = new FileOutputStream("text.txt");
  f.writeTo(f2);
  f2.close();
  System.out.println("Doing a reset");
  f.reset();
  for(int i=0;i<3;i++){
   f.write('X');
  }
  System.out.println(f.toString());
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值