Java.io.FileInputStream.read() 方法
描述
java.io.FileInputStream.read(byte[] b) 从此文件输入流中读取最多 b.length 到字节数组。 该方法会阻塞,直到某些输入可用。
声明
以下是 java.io.FileInputStream.read(byte[] b) 方法的声明 −
public int read(byte[] b)
参数
b − 读取数据的字节数组。
返回值
这些方法返回读入缓冲区的总字节数,如果没有更多数据要读取,则返回 -1。
异常
IOException − 如果发生 I/O 错误。
示例
下面的例子展示了 java.io.FileInputStream.read(byte[] b) 方法的使用。
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);
// 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;
// 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: 4 Bytes read: ABCD

