Java.io.DataInputStream.read() 方法
描述
java.io.DataInputStream.read(byte[] b) 方法从包含的输入流中读取字节数并将它们分配到缓冲区 b 中。 该方法被阻塞,直到输入数据可用、抛出异常或检测到文件结尾。
声明
以下是 java.io.DataInputStream.read(byte[] b) 方法的声明 −
public final int read(byte[] b)
参数
b − 从此流中读取数据的缓冲区数组。
返回值
流中的总字节数,否则 -1 如果流已到达末尾。
异常
IOException − 如果发生 I/O 错误,则无法读取第一个字节,或者在此方法之前调用 close()。
NullPointerException − 如果 b 为空。
示例
下面的例子展示了 java.io.DataInputStream.read(byte[] b) 方法的使用。
package com.tutorialspoint;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
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 input stream from file input stream
is = new FileInputStream("c:\\test.txt");
// create data input stream
dis = new DataInputStream(is);
// count the available bytes form the input stream
int count = is.available();
// create buffer
byte[] bs = new byte[count];
// read data into buffer
dis.read(bs);
// for each byte in the buffer
for (byte b:bs) {
// convert byte into character
char c = (char)b;
// print the character
System.out.print(c+" ");
}
} catch(Exception e) {
// if any I/O error occurs
e.printStackTrace();
} finally {
// releases any associated system files with this stream
if(is!=null)
is.close();
if(dis!=null)
dis.close();
}
}
}
假设我们有一个文本文件c:/test.txt,其内容如下。 该文件将用作我们示例程序的输入 −
ABCDEFGH
让我们编译并运行上面的程序,这将产生下面的结果 −
A B C D E F G H

