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


Java Java.io.DataInputStream.readFully()用法及代碼示例


描述

這個java.io.DataInputStream.readFully(byte[] b)方法從輸入流中讀取字節並將它們分配到緩衝區數組 b 中。

它會阻塞,直到發生以下情況之一 -

  • b.輸入數據的長度字節可用。
  • 檢測到文件結尾。
  • 如果發生任何 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.tutorialspoint;

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!

相關用法


注:本文由純淨天空篩選整理自 Java.io.DataInputStream.readFully() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。