当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。