Java BufferedOutputStream write()方法

java.io.BufferedInputStream.write(byte[], int, int) 将指定字节输入流中的字节写入给定字节数组,从给定的偏移量开始。

1 语法

public void write(byte[] b, int off, int len)

2 参数

b:字节数组作为源数据

off:源中的起始偏移量

len:写入流的字节数

3 返回值

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 *  java.io.BufferedInputStream.write(byte[], int, int)方法的例子
 */
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class Demo {
    public static void main(String[] args) throws Exception {
        BufferedOutputStream bos = null;
        ByteArrayOutputStream baos = null;
        try {
            // create new output streams.
            baos = new ByteArrayOutputStream();
            bos = new BufferedOutputStream(baos);

            // assign values to the byte array
            byte[] bytes = {1, 2, 3, 4, 5};

            // write byte array to the output stream
            bos.write(bytes, 0, 5);

            // flush the bytes to be written out to baos
            bos.flush();

            for (byte b:baos.toByteArray()) {

                // prints byte
                System.out.print(b);
            }
        } catch(IOException e) {
            // if any IOError occurs
            e.printStackTrace();
        } finally {
            // releases any system resources associated with the stream
            if(baos!=null)
                baos.close();
            if(bos!=null)
                bos.close();
        }
    }
}

输出结果为:

12345

热门文章

优秀文章