Java.io.FileInputStream.read() 方法
描述
java.io.FileInputStream.read(byte[] b, int off, int len) 从此输入流中读取多达 len 个字节的数据到一个字节数组中,从目标中的 offset off 开始 数组 b。
声明
以下是 java.io.FileInputStream.read(byte[] b, int off, int len) 方法的声明 −
public int read(byte[] b, int off, int len)
参数
b − 读取数据的字节数组。
off − 目标数组 b 中的起始偏移量。
len − 要读取的最大字节数。
返回值
该方法返回读入缓冲区的总字节数。
异常
IOException − 如果发生 I/O 错误。
NullPointerException − 如果 b 为空。
IndexOutOfBoundsException − 如果 len 或 off 为负数,或者 b.length-off 大于 b.length。
示例
下面的例子展示了 java.io.FileInputStream.read(byte[] b, int off, int len) 方法的使用。
package com.tutorialspoint;
import java.io.IOException;
import java.io.FileInputStream;
public class FileInputStreamDemo {
public static void main(String[] args) throws IOException {
FileInputStream fis = null;
int i = 0;
char c;
byte[] bs = new byte[4];
try {
// create new file input stream
fis = new FileInputStream("C://test.txt");
// read bytes to the buffer
i = fis.read(bs, 2, 1);
// prints
System.out.println("Number of bytes read: "+i);
System.out.print("Bytes read: ");
// for each byte in buffer
for(byte b:bs) {
// converts byte to character
c = (char)b;
if(b == 0)
c = '-';
// print
System.out.print(c);
}
} catch(Exception ex) {
// if any error occurs
ex.printStackTrace();
} finally {
// releases all system resources from the streams
if(fis!=null)
fis.close();
}
}
}
假设我们有一个文本文件c:/test.txt,其内容如下。 该文件将用作我们示例程序的输入 −
ABCDEF
让我们编译并运行上面的程序,这将产生下面的结果 −
Number of bytes read: 1 Bytes read: --A-

