Java-io-bytearrayinputstream-read-len
提供:Dev Guides
Java.io.ByteArrayInputStream.read()メソッド
説明
- java.io.ByteArrayInputStream.read(byte [] b、int off、int len)*メソッドは、この入力ストリームからlenバイトのデータをバイトの配列に読み込みます。 read()メソッドはブロックしません。
宣言
以下は* java.io.ByteArrayInputStream.read(byte [] b、int off、int len)*メソッドの宣言です-
public int read(byte[] b, int off, int len)
パラメーター
- b -データはこのバッファに読み込まれます
- off -宛先配列bから始まるオフセット
- len -読み取られた最大バイト数
戻り値
バッファに読み込まれたバイト数。 ストリームが終了した場合、-1を返します。
例外
- NullPointerException -bがnullの場合。
- IndexOutOfBoundsException -lenがオフセット後の入力ストリームの長さより大きい場合、offは負、またはlenは負です。
例
次の例は、java.io.ByteArrayInputStream.read(byte [] b、int off、int len)メソッドの使用方法を示しています。
package com.finddevguides;
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);
//create buffer
byte[] b = new byte[4];
int num = bais.read(b, 2, 2);
//number of bytes read
System.out.println("Bytes read: "+num);
//for each byte in a buffer
for (byte s :b) {
//covert byte to char
char c = (char)s;
//prints byte
System.out.print(s);
if(s == 0)
//if byte is 0
System.out.println(": Null");
else
//if byte is not 0
System.out.println(": "+c);
}
} catch(Exception e) {
//if I/O error occurs
e.printStackTrace();
} finally {
if(bais!=null)
bais.close();
}
}
}
上記のプログラムをコンパイルして実行すると、次の結果が生成されます-
Bytes read: 2
0: Null
0: Null
65: A
66: B