全屏
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 cn.sxt;
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
System.out.print("" + (char) cbuf[i]);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}}
让我们编译和运行上面的程序,这将产生以下结果:Hello
分享到:
0评论