Java OutputStream.write()将数据写入输出流

定义

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

b:指定的字节;off:数组b中将写入数据的初始偏移量;len:要读取的最大字节数

返回

无任何返回

异常

IOException:I/O 错误或者流已经关闭。

例子

public static void main(String[] args)
{
    OutputStream os = null;
    try
    {
        String str = "欢迎加入JAVASCHOOL";
        byte[] bytes = str.getBytes();
        for(int i = 0; i < bytes.length; i++)
        {
            os.write(bytes[i]);
        }
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        if(os != null)
        {
            try
            {
                os.close(); //关闭资源
            }
            catch(IOException e)
            {}
        }
    }
    OutputStream out = System.out;
    try
    {
        byte[] bs = "一起来学习JAVA".getBytes();
        out.write(bs);
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        out.close(); // 关闭输出流
    }
}

1. write(int b) 作为抽象类中唯一的抽象方法,(非抽象)子类必须实现这个方法。这个方法用得比较少,一般在子类的实现中使用

2. write(byte b[])直接输出一个字节数组中的全部内容

3. write(byte b[], int off, int len) 要输出的内容已存储在了字节数组b[]中,但并非全部输出,只输出从数组off位置开始的len个字节。

4. 输出了流里面的内容,一定更要记得关闭资源。