Java.io.ObjectInputStream.read() 方法



描述

java.io.ObjectInputStream.read(byte[] buf, int off, int len) 方法讀取到位元組陣列中。此方法將阻塞,直到有輸入可用。考慮使用 java.io.DataInputStream.readFully 讀取正好“length”個位元組。

宣告

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

public int read(byte[] buf, int off, int len)

引數

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

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

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

返回值

此方法返回實際讀取的位元組數,當到達流的末尾時返回 -1。

異常

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

示例

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

package com.tutorialspoint;

import java.io.*;

public class ObjectInputStreamDemo {
   public static void main(String[] args) {
      byte[] cbuf = new byte[10];
      
      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("Hello World");
         oout.flush();

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

         // read from the stream into an array
         ois.read(cbuf, 0, 7);

         // print cbuf
         for (int i = 0; i < 7; i++) {
            System.out.print("" + (char) cbuf[i]);
         }
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

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

Hello
java_io_objectinputstream.htm
廣告