Java.io.InputStream.read() 方法
描述
java.io.InputStream.read(byte[] b) 方法从输入流中读取 b.length 个字节到缓冲区数组 b。 读取的字节以整数形式返回。
声明
以下是 java.io.InputStream.read(byte[] b) 方法的声明 −
public int read(byte[] b)
参数
b − 目标字节数组。
返回值
该方法返回实际读入缓冲区的字节数,如果到达流的末尾,则返回 -1。
异常
IOException − 如果发生 I/O 错误。
NullPointerException − 如果 b 为空。
示例
下面的例子展示了 java.io.InputStream.read(byte[] b) 方法的使用。
package com.tutorialspoint;
import java.io.FileInputStream;
import java.io.InputStream;
public class InputStreamDemo {
public static void main(String[] args) throws Exception {
InputStream is = null;
byte[] buffer = new byte[5];
char c;
try {
// new input stream created
is = new FileInputStream("C://test.txt");
System.out.println("Characters printed:");
// read stream data into buffer
is.read(buffer);
// for each byte in the buffer
for(byte b:buffer) {
// convert byte to character
c = (char)b;
// prints character
System.out.print(c);
}
} catch(Exception e) {
// if any I/O error occurs
e.printStackTrace();
} finally {
// releases system resources associated with this stream
if(is!=null)
is.close();
}
}
}
假设我们有一个文本文件c:/test.txt,其内容如下。 该文件将用作我们示例程序的输入 −
ABCDE
让我们编译并运行上面的程序,这将产生下面的结果 −
Characters printed: ABCDE

