Java DataOutputStream write()方法

java.io.BufferedInputStream.write(int b) 用于将指定的字节写入基础输出流。

1 语法

public void write(int b)

2 参数

b:源字节,为整数。

3 返回值

4 示例 

package com.yiidian;

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

public class Demo {
    public static void main(String[] args) throws IOException {
        ByteArrayOutputStream baos = null;
        DataOutputStream dos = null;
        int[] buf = {65, 66, 67, 68, 69, 70, 71};

        try {
            // create byte array output stream
            baos = new ByteArrayOutputStream();

            // create data output stream
            dos = new DataOutputStream(baos);

            // write to the stream from integer array
            for(int i: buf) {
                dos.write(i);
            }

            // flushes bytes to underlying output stream
            dos.flush();

            // for each byte in the baos buffer content
            for(byte b:baos.toByteArray()) {

                // convert byte to char
                char c = (char)b;

                // print character
                System.out.print(c);
            }

        } catch(Exception e) {
            // if any error occurs
            e.printStackTrace();
        } finally {
            // releases all system resources from the streams
            if(baos!=null)
                baos.close();
            if(dos!=null)
                dos.close();
        }
    }
}

输出结果为:

ABCDEFG

热门文章

优秀文章