當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java DataOutputStream writeBoolean()用法及代碼示例

DataOutputStream類writeBoolean()方法

  • writeBoolean() 方法可在java.io包。
  • writeBoolean() 方法用於將給定的布爾字節寫入基本輸出流,因此寫入的變量計數器在成功執行時加 1。
  • writeBoolean() 方法是一個非靜態方法,它隻能通過類對象訪問,如果我們嘗試使用類名訪問方法,那麽我們將得到一個錯誤。
  • writeBoolean() 方法可能在寫入布爾值時拋出異常。
    IOException:在獲取任何輸入/輸出錯誤時可能會拋出此異常。

用法:

    public final void writeBoolean(boolean val);

參數:

  • boolean val– 表示要寫入基本數據輸出流的布爾值。

返回值:

該方法的返回類型是void,它什麽都不返回。

例:

// Java program to demonstrate the example 
// of void writeBoolean(boolean val) method 
// of DataOutputStream

import java.io.*;

public class WriteBooleanOfDOS {
 public static void main(String[] args) throws Exception {
  ByteArrayOutputStream baos_stm = null;
  DataOutputStream dos_stm = null;

  boolean[] bool = {
   false,
   false,
   true,
   false
  };

  try {
   // Instantiates ByteArrayOutputStream, DataOutputStream
   baos_stm = new ByteArrayOutputStream();
   dos_stm = new DataOutputStream(baos_stm);

   for (boolean val:bool) {
    // By using writeBoolean() method isto write
    // boolean value from the given bool array
    // to the dos_stm stream i.e. o represents
    // false and 1 represents true
    dos_stm.writeBoolean(val);
   }

   // By using toByArray() method isto
   // convert the stream baos_stm to byte 
   // array
   byte[] by = baos_stm.toByteArray();

   // Loop to display each byte to the
   // baos_stm data till its end

   for (byte val:by) {
    // Display byte
    System.out.println("dos_stm.writeBoolean():" + val);
   }
  } catch (Exception ex) {
   System.out.println(ex.toString());
  } finally {
   // this block is to free all necessary system 
   // resources linked with the stream

   if (baos_stm != null)
    baos_stm.close();

   if (dos_stm != null)
    dos_stm.close();
  }
 }
}

輸出

dos_stm.writeBoolean():0
dos_stm.writeBoolean():0
dos_stm.writeBoolean():1
dos_stm.writeBoolean():0


相關用法


注:本文由純淨天空篩選整理自Preeti Jain大神的英文原創作品 Java DataOutputStream writeBoolean() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。