例子
以下示例显示java.io.ByteArrayInputStream.read()方法的用法。
package com.jc2182;
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