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

