温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java _io_字节数组输出流

发布时间:2020-07-31 08:43:05 来源:网络 阅读:220 作者:wx5d21d5e6e5ab1 栏目:编程语言

字节数组输出流,无需添加目的地,因为数据会被自动输入内存的缓冲区,需通过
.toByteArray()或.toString()拿到数据
因为需要使用子类ByteArrayOutputStream的新方法,所以不能写父类OutputStream对象
ByteArrayOutputStream os=new ByteArrayOutputStream();

因为数据写入了缓冲区,所以需要通过.toByteArray()和.toString()手动拿取

步骤:
创建目的地字节数组(用来存放从缓冲区拿来的数据): Byte[] last=null;
选择流: ByteArrayOutputStream os;
编码:字符串到字节
操作:os.write(byte[],0,byte,length)写入
获取数据:last=os.toByteArray();
System.out.println(new String(last,0,last.length)//或last.length可替换成os.size()
解码

public class test{
    public static void main(String[]args)
    {
        //创建目的地
        byte[] last=null;
        //选择流(新增方法)
        ByteArrayOutputStream os=null;  //不用OutputStream,是因为要用子类ByteArrayOutputStream的新增方法
        try {
        os =new ByteArrayOutputStream();

        String s="hello world";
        byte[] data=s.getBytes(); //编码,字符串到字符数组

        os.write(data,0,data.length);
        os.flush();
        //获取数据
        last=os.toByteArray();
        System.out.println(last.length);
        System.out.println(last.length+"---"+new String(last,0,last.length));//或者os.size()

    }catch(IOException e)
    {
        e.printStackTrace();
    }

}

}

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI