void write(byte[] b, int off, int len)
描述 (Description)
java.io.OutputStream.write(byte[] b, int off, int len)方法将从偏移量off开始的指定字节数组中的len个字节写入此输出流。 write(b,off,len)的一般契约是数组b中的一些字节按顺序写入输出流; element b [off]是写入的第一个字节,b [off + len-1]是此操作写入的最后一个字节。
OutputStream的write方法在每个要写出的字节上调用一个参数的write方法。 鼓励子类重写此方法并提供更有效的实现。
如果b为null,则抛出NullPointerException。 如果off为负数,或len为负数,或者off + len大于数组b的长度,则抛出IndexOutOfBoundsException。
声明 (Declaration)
以下是java.io.OutputStream.write()方法的声明。
public void write(byte[] b, int off, int len)
参数 (Parameters)
b - 数据。
off - 数据中的起始偏移量。
len - 要写入的字节数。
返回值 (Return Value)
此方法不返回值。
异常 (Exception)
IOException - 如果发生I/O错误。 特别是,如果输出流已关闭,则抛出IOException。
例子 (Example)
以下示例显示了java.io.OutputStream.write()方法的用法。
package com.iowiki;
import java.io.*;
public class OutputStreamDemo {
public static void main(String[] args) {
byte[] b = {'h', 'e', 'l', 'l', 'o'};
try {
// create a new output stream
OutputStream os = new FileOutputStream("test.txt");
// craete a new input stream
InputStream is = new FileInputStream("test.txt");
// write something
os.write(b, 0, 3);
// read what we wrote
for (int i = 0; i < 3; i++) {
System.out.print("" + (char) is.read());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
让我们编译并运行上面的程序,这将产生以下结果 -
hel