java.io.OutputStream.write(byte[] b, int off, int len)方法实例

参考地址:https://blog.csdn.net/LWJdear/article/details/72845345

java.io.OutputStream.write(byte[] b, int off, int len) 方法从指定的字节数组开始到当前输出流关闭写入len字节。一般的合约write(b, off, len),一些在数组b中的字节写入,以便输出流;元素b[off]是写入的第一个字节和b[off+len-1]是写的这个操作的最后一个字节。OutputStream的write方法调用的每个被写出其中一个字节参数的write方法。子类被鼓励重写此方法,并提供了一个更有效的实现。

如果b为null,一个NullPointerException异常抛出。如果断为负,或len为负,或者off + len位置大于数组b的长度,则抛出IndexOutOfBoundsException。

声明

以下是java.io.OutputStream.write()方法的声明

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

参数

  • b -- 数据

  • off -- 在数据偏移的开始。

  • len -- 写入的字节数

返回值

此方法无返回值。

异常

  • IOException -- 如果发生I/ O错误。特别是IOException,如果是输出流被关闭抛出。

例子

下面的示例演示java.io.OutputStream.write()方法的用法。

package com.yiibai;

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

下面的示例演示java.io.OutputStream.write()方法的用法,循环多次写入os.write  off偏移指的是 b数据中偏移量。


下面的示例演示java.io.OutputStream.write()方法的用法。

package com.yiibai;


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
	 for (int i = 0; i < 3 ; i++ ){
	    os.write(b, 1, 4);
	 }


         // read what we wrote
         for (int i = 0; i < 9; i++) {
            System.out.print("" + (char) is.read());
         }


      } catch (Exception ex) {
         ex.printStackTrace();
      }




   }
}



让我们编译和运行上面的程序,这将产生以下结果:

elloelloe



猜你喜欢

转载自blog.csdn.net/dodod2012/article/details/80581162
int