Java.io.DataInputStream.readFully() 方法
描述
java.io.DataInputStream.readFully(byte[] b) 方法从输入流中读取 len 个字节。
它会阻塞,直到出现以下情况之一 −
- b.length 字节的输入数据可用。
- 检测到文件结尾。
- 如果发生任何 I/O 错误。
声明
以下是 java.io.DataInputStream.readFully(byte[] b, int off, int len) 方法的声明 −
public final void readFully(byte[] b, int off, int len)
参数
b − 目标缓冲区。
off − 数据中的偏移量。
len − 要读取的字节数。
返回值
此方法不返回任何值。
异常
IOException − 如果发生任何 I/O 错误或流已关闭。
EOFException − 如果此输入流之前到达末尾。
示例
下面的例子展示了 java.io.DataInputStream.readFully(byte[] b, int off, int len) 方法的使用。
package com.tutorialspoint;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class DataInputStreamDemo {
public static void main(String[] args) throws IOException {
InputStream is = null;
DataInputStream dis = null;
try {
// create file input stream
is = new FileInputStream("c:\\test.txt");
// create new data input stream
dis = new DataInputStream(is);
// available stream to be read
int length = dis.available();
// create buffer
byte[] buf = new byte[length];
// read the full data into the buffer
dis.readFully(buf, 4, 5);
// for each byte in the buffer
for (byte b:buf) {
char c = '0';
if(b!=0)
c = (char)b;
// prints character
System.out.print(c);
}
} catch(Exception e) {
// if any error occurs
e.printStackTrace();
} finally {
// releases all system resources from the streams
if(is!=null)
is.close();
if(dis!=null)
dis.close();
}
}
}
假设我们有一个文本文件c:/test.txt,其内容如下。 该文件将用作我们示例程序的输入 −
Hello World!
让我们编译并运行上面的程序,这将产生下面的结果 −
0000Hello000

