Java-io-datainputstream-readfully-len
提供:Dev Guides
Java.io.DataInputStream.readFully()メソッド
説明
- java.io.DataInputStream.readFully(byte [] b)*メソッドは、入力ストリームからlenバイトを読み取ります。
以下の条件のいずれかが発生するまでブロックします-
- b.lengthバイトの入力データが利用可能です。
- ファイルの終わりが検出されました。
- I/Oエラーが発生した場合。
宣言
以下は、* java.io.DataInputStream.readFully(byte [] b、int off、int len)*メソッドの宣言です-
public final void readFully(byte[] b, int off, int len)
パラメーター
- b -宛先バッファ。
- off -データへのオフセット。
- len -読み取るバイト数。
戻り値
このメソッドは値を返しません。
例外
- IOException -I/Oエラーが発生した場合、またはストリームが閉じられた場合。
- EOFException -この入力ストリームが前に終了した場合。
例
次の例は、java.io.DataInputStream.readFully(byte [] b、int off、int len)メソッドの使用方法を示しています。
package com.finddevguides;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class DataInputStreamDemo {
public static void main(String[] args) throws IOException {
InputStream is = null;
DataInputStream dis = null;
try {
//create file input stream
is = new FileInputStream("c:\\test.txt");
//create new data input stream
dis = new DataInputStream(is);
//available stream to be read
int length = dis.available();
//create buffer
byte[] buf = new byte[length];
//read the full data into the buffer
dis.readFully(buf, 4, 5);
//for each byte in the buffer
for (byte b:buf) {
char c = '0';
if(b!=0)
c = (char)b;
//prints character
System.out.print(c);
}
} catch(Exception e) {
//if any error occurs
e.printStackTrace();
} finally {
//releases all system resources from the streams
if(is!=null)
is.close();
if(dis!=null)
dis.close();
}
}
}
テキストファイル* c:/test.txt*があり、次の内容があるとします。 これは、サンプルプログラムの入力として使用されます-
Hello World!
上記のプログラムをコンパイルして実行すると、次の結果が生成されます-
0000Hello000