Java.io.DataOutputStream.writeBoolean()方法範例


java.io.BufferedInputStream.writeBoolean(boolean v) 方法寫入指定的源位元組到基礎輸出流。成功呼叫寫入計數器加1遞增。

宣告

以下是java.io.DataOutputStream.writeBoolean(boolean v)方法的宣告:

public final void writeBoolean(boolean v)

引數

  • b -- 一個布林值寫入基礎流。

返回值

此方法不返回任何值。

異常

  • IOException --如果發生I/ O錯誤。

例子

下面的範例演示java.io.DataOutputStream.writeBoolean(boolean v) 方法的用法。

package com.yiibai;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class DataOutputStreamDemo {
   public static void main(String[] args) throws IOException {
      
      ByteArrayOutputStream baos = null;
      DataOutputStream dos = null;
      boolean[] bools = {true, false, false, true, true, true};
      
      try{
         // create byte array output stream
         baos = new ByteArrayOutputStream();
         
         // create data output stream
         dos = new DataOutputStream(baos);
         
         // write to the stream from boolean array
         for(boolean bool: bools)
         {
            dos.writeBoolean(bool);
         }
         // flushes bytes to underlying output stream
         dos.flush();
   
         // for each byte in the baos buffer content
         for(byte b:baos.toByteArray())
         {   
            // print character
            System.out.print(b);
         }
      }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();
      }
   }
}

讓我們編譯和執行上面的程式,這將產生以下結果:

100111