JavaSE 高级 第10节 字节数组输出流ByteArrayOutputStream

2016-07-24

1,ByteArrayOutputStream

         FileOutputStream 把文件作为写入的目的地

         ByteArrayOutputStream 把字节数组作为写入的目的地

package com.java1995;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;

public class Test {

    public static void main(String[] args) {
        String str = "abcdefghijklmnopqrstuvwxyz";
        byte[] b = str.getBytes();

        ByteArrayInputStream bais = new ByteArrayInputStream(b);
        BufferedInputStream bis = new BufferedInputStream(bais);
        int temp = 0;
        try {
            temp = bis.read();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        int count = 0;
        while (temp != -1) {
            System.out.print((char) temp);
            try {
                temp = bis.read();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(count++);
        }
        System.out.println(count);

    }
}

package com.java1995;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class TestByteArrayOutputStream {

    public static void main(String[] args) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        String temp = "hello world hello everyone!";
        byte[] b = temp.getBytes();

        try {
            bos.write(b);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(bos.toString());

        byte[] b1 = bos.toByteArray();
        for (int i = 0; i < b1.length; i++) {
            System.out.print((char) b1[i]);

        }
    }
}

【参考资料】

[1] Java轻松入门经典教程【完整版】

posted @ 2016-07-24 17:34  岑亮  阅读(261)  评论(0编辑  收藏  举报