int read(byte[] b, int off, int len)
描述 (Description)
java.io.DataInputStream.read(byte[] b, int off, int len)方法从包含的输入流中读取len个字节,并在缓冲区b中从b[off]开始分配它们。 该方法被阻止,直到输入数据可用,抛出异常或检测到文件结尾。
声明 (Declaration)
以下是java.io.DataInputStream.read(byte[] b, int off, int len)方法的声明 -
public final int read(byte[] b, int off, int len)
参数 (Parameters)
b - 从输入流中读取数据的字节[]。
off - b []中的起始偏移量。
len - 读取的最大字节数。
返回值 (Return Value)
读取的总字节数,如果流已到达结束,则返回-1。
异常 (Exception)
IOException - 如果发生I/O错误,则无法读取第一个字节,或者在此方法之前调用close()。
NullPointerException - 如果b为null。
IndexOutOfBoundsException - 如果len大于b.length - off,则off为负,或len为负
例子 (Example)
以下示例显示了java.io.DataInputStream.read(byte [] b,int off,int len)方法的用法。
package com.iowiki;
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 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 len data into buffer starting at off
dis.read(bs, 4, 3);
// for each byte in the buffer
for (byte b:bs) {
// convert byte into character
char c = (char)b;
// empty byte as char '0'
if(b == 0)
c = '0';
// 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
让我们编译并运行上面的程序,这将产生以下结果 -
0000ABC0