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


Java ObjectInputStream readFully()用法及代碼示例


ObjectInputStream 類的 readFully() 方法用於讀取字節,直到完全讀取 objectinputstream 中的所有字節。它需要 3 個參數作為存儲數據的緩衝區、從哪裏開始讀取以及讀取多少字節。

用法

public void readFully(byte[] buf) throws IOException
public void readFully(byte[] buf, int off, int len) throws IOException

參數

buf- 讀取數據的緩衝區

off- 數據數組 buf 中的起始偏移量

len- 要讀取的最大字節數

返回

NA

拋出

NullPointerException - 如果 buf 為空。

IndexOutOfBoundsException - 如果 off 為負,len 為負,或者 len 大於 buf.length - off。

EOFException - 如果到達文件末尾。

IOException - 如果發生其他 I/O 錯誤。

例子1

import java.io.*;
public class ObjectInputStreamreadFullyExample1 {
   public static void main(String[] args) {
      String s = "welcome to javatpoint";
      try {
         // create a new file with an ObjectOutputStream
         FileOutputStream outstream = new FileOutputStream("file1.txt");
         ObjectOutputStream objoutstream = new ObjectOutputStream(outstream);

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

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

         // read and print the whole content
         byte[] bt = new byte[22];
         objinstream.readFully(bt);
         String arr = new String(bt);
         System.out.println("" + arr);
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

輸出:

welcome to javatpoint

例子2

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectInputStreamreadFullyExample2 {
   public static void main(String[] args) throws IOException {
      String s = "welcom to javatpoint";
      
      try {
         // create a new file with an ObjectOutputStream
         FileOutputStream outstream = new FileOutputStream("file1.txt");
         ObjectOutputStream objoutstream = new ObjectOutputStream(outstream);

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

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

         // read and print the whole content
         byte[] bt = new byte[22];
        objinstream.readFully(bt, 10, 9);
        String arr = new String(bt);
         
         System.out.println("" + arr);
          
          }
       catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

輸出:

welcome




相關用法


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