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


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

DataOutputStream類flush()方法

  • flush() 方法可在java.io包。
  • flush() 方法用於刷新此流並強製將字節寫入基本流。
  • flush() 方法是一個非靜態方法,它隻能通過類對象訪問,如果我們嘗試使用類名訪問方法,那麽我們將得到一個錯誤。
  • flush() 方法可能會在刷新流時拋出異常。
    IOException: 獲取任何輸入/輸出錯誤時可能會拋出此異常。

用法:

    public void flush();

參數:

  • 它不接受任何參數。

返回值:

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

例:

// Java program to demonstrate the example 
// of void flush() method of DataOutputStream

import java.io.*;

public class FlushOfDOS {
 public static void main(String[] args) throws IOException {
  InputStream is_stm = null;
  DataInputStream dis_stm = null;
  FileOutputStream fos_stm = null;
  DataOutputStream dos_stm = null;
  byte[] b_arr = {
   12,
   20,
   45,
   98,
   75,
   69,
   30,
   58,
   47,
   61,
   83,
   55
  };

  try {
   // Instantiate FileInputStream, 
   // DataInputStream, FileOutputStream
   // and DataOutputStream 

   fos_stm = new FileOutputStream("C:\\Users\\Preeti Jain\\Desktop\\programs\\includehelp.txt");
   dos_stm = new DataOutputStream(fos_stm);
   is_stm = new FileInputStream("C:\\Users\\Preeti Jain\\Desktop\\programs\\includehelp.txt");
   dis_stm = new DataInputStream(is_stm);

   // Loop to write each byte till end
   for (byte val:b_arr) {
    // By using write() method isto
    // write a byte value to the
    // DataOutputStream dos_stm
    dos_stm.write(val);
   }

   // By using flush() method isto
   // flush the stream and forces bytes
   // are written out immediately of any 
   // buffered output
   dos_stm.flush();

   // Loop To Read Available Data till end
   while (dis_stm.available() > 0) {
    // By using read() method isto read 
    // byte from dis_stm
    int in = dis_stm.read();
    System.out.println("dis_stm.read():" + in );
   }
  } catch (Exception ex) {
   System.out.println(ex.toString());
  } finally {
   // To free system resources linked
   // with these streams
   if (is_stm != null)
    is_stm.close();

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

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

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

輸出

dis_stm.read():12
dis_stm.read():20
dis_stm.read():45
dis_stm.read():98
dis_stm.read():75
dis_stm.read():69
dis_stm.read():30
dis_stm.read():58
dis_stm.read():47
dis_stm.read():61
dis_stm.read():83
dis_stm.read():55


相關用法


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