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


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

DataOutputStream類size()方法

  • size() 方法可在java.io包。
  • size() 方法用於返回此流的大小,或者換句話說,我們可以說它返回包含寫入字節的變量計數器的值。
  • size() 方法是一個非靜態方法,它隻能通過類對象訪問,如果我們嘗試使用類名訪問方法,那麽我們將得到一個錯誤。
  • size() 方法返回大小時不拋出異常。

用法:

    public final int size();

參數:

  • 它不接受任何參數。

返回值:

該方法的返回類型是int,它返回變量計數器的最後一個值。

例:

// Java program to demonstrate the example 
// of int size() method of DataOutputStream

import java.io.*;

public class SizeOfDOS {
 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);
   }

   // 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 );
   }

   System.out.println();

   // By using size() method isto return
   // size of this stream
   int size = dos_stm.size();

   System.out.println("dos_stm.size():" + size);
  } 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

dos_stm.size():12


相關用法


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