Java.io.DataInputStream.readFully()方法範例


java.io.DataInputStream.readFully(byte[] b) 方法讀取輸入流中的位元組,並分配該等到緩衝區陣列b中。

它會阻止,直到下面條件之一發生:

  • b.length 個的位元組可輸入資料。
  • 檔案結束檢測。
  • 如果發生任何I/ O錯誤。

宣告

以下是java.io.DataInputStream.readFully(byte[] b) 方法的宣告:

public final void readFully(byte[] b)

引數

  • NA

返回值

此方法不返回任何值。

異常

  • IOException -- 如果發生任何I/O錯誤,或者該流已關閉。

  • EOFException -- 如果此輸入流之前到達末尾。

例子

下面的例子顯示java.io.DataInputStream.readFully(byte[] b) 方法的用法。

package com.yiibai;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class DataInputStreamDemo {
   public static void main(String[] args) throws IOException {
      
      InputStream is = null;
      DataInputStream dis = null;
      
      try{
         // create file input stream
         is = new FileInputStream("c:\test.txt");
         
         // create new data input stream
         dis = new DataInputStream(is);
         
         // available stream to be read
         int length = dis.available();
         
         // create buffer
         byte[] buf = new byte[length];
         
         // read the full data into the buffer
         dis.readFully(buf);
         
         // for each byte in the buffer
         for (byte b:buf)
         {
            // convert byte to char
            char c = (char)b; 
            
            // prints character
            System.out.print(c);
         }
      }catch(Exception e){
         // if any error occurs
         e.printStackTrace();
      }finally{
         
         // releases all system resources from the streams
         if(is!=null)
            is.close();
         if(dis!=null)
            dis.close();
      }
   }
}

假設我們有一個文字檔案c:/ test.txt,它具有以下內容。該檔案將被用作輸入到我們的範例程式:

Hello World!

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

Hello World!