int read(byte[] b)
描述 (Description)
java.io.InputStream.read(byte[] b)方法读取从输入流到缓冲区数组b的b.length个字节数。 读取的字节以整数形式返回。
声明 (Declaration)
以下是java.io.InputStream.read(byte[] b)方法的声明 -
public int read(byte[] b)
参数 (Parameters)
b - 目标字节数组。
返回值 (Return Value)
该方法返回实际读入缓冲区的字节数,如果到达流末尾,则返回-1。
异常 (Exception)
IOException - 如果发生I/O错误。
NullPointerException - 如果b为null。
例子 (Example)
以下示例显示了java.io.InputStream.read(byte [] b)方法的用法。
package com.iowiki;
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