Java.io.ByteArrayInputStream.read() 方法
描述
java.io.ByteArrayInputStream.read() 方法从此输入流中读取下一个字节。 read() 方法不会阻塞
声明
以下是 java.io.ByteArrayInputStream.read() 方法的声明 −
public int read()
参数
NA
返回值
在 0-255 范围内以 int 形式返回值字节。 如果流已经结束,则返回 -1。
异常
NA
示例
下面的例子展示了 java.io.ByteArrayInputStream.read() 方法的使用。
package com.tutorialspoint;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class ByteArrayInputStreamDemo {
public static void main(String[] args) throws IOException {
byte[] buf = {65, 66, 67, 68, 69};
ByteArrayInputStream bais = null;
try {
// create new byte array input stream
bais = new ByteArrayInputStream(buf);
int b =0;
// read till the end of the stream
while((b = bais.read())!=-1) {
// convert byte to character
char c = (char)b;
// print
System.out.println("byte :"+b+"; char : "+ c);
}
System.out.print(bais.read()+" Reached the end");
} catch(Exception e) {
// if I/O error occurs
e.printStackTrace();
} finally {
if(bais!=null)
bais.close();
}
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
byte :65; char : A byte :66; char : B byte :67; char : C byte :68; char : D byte :69; char : E -1 Reached the end