Java.io.ObjectInputStream.readFully() 方法



描述

java.io.ObjectInputStream.readFully(byte[] buf, int off, int len) 方法讀取位元組,並在所有位元組都讀取完畢之前阻塞。

宣告

以下是 java.io.ObjectInputStream.readFully() 方法的宣告。

public void readFully(byte[] buf)

引數

  • buf − 讀取資料到的緩衝區。

  • off − 資料的起始偏移量。

  • len − 要讀取的最大位元組數。

返回值

此方法不返回值。

異常

  • EOFException − 如果到達檔案末尾。

  • IOException − 如果發生 I/O 錯誤。

示例

以下示例演示了 java.io.ObjectInputStream.readFully() 方法的使用。

package com.tutorialspoint;

import java.io.*;

public class ObjectInputStreamDemo {
   public static void main(String[] args) {
      String s = "Hello World";
      
      try {
         // create a new file with an ObjectOutputStream
         FileOutputStream out = new FileOutputStream("test.txt");
         ObjectOutputStream oout = new ObjectOutputStream(out);

         // write something in the file
         oout.writeUTF(s);
         oout.flush();

         // create an ObjectInputStream for the file we created before
         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));

         // read and print from index 0 to 7
         byte[] b = new byte[13];
         ois.readFully(b, 0, 7);
         String array = new String(b);
         System.out.println("" + array);
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

讓我們編譯並執行上述程式,這將產生以下結果:

Hello
java_io_objectinputstream.htm
廣告