Java-io-filterinputstream-read
提供:Dev Guides
Java.io.FilterInputStream.read()Method
説明
- java.io.FilterInputStream.read()*メソッドは、入力ストリームからデータの次のバイトを読み取ります。 返される値バイトの範囲は0〜255です。 ファイルの終わりに達すると、メソッドは-1を返します。
宣言
以下は* java.io.FilterInputStream.read()*メソッドの宣言です-
public int read()
パラメーター
NA
戻り値
このメソッドは、データの次のバイトを返します。ストリームの終わりに達した場合は-1を返します。
例外
*IOException* -I/Oエラーが発生した場合
例
次の例は、java.io.FilterInputStream.read()メソッドの使用法を示しています。
package com.finddevguides;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public class FilterInputStreamDemo {
public static void main(String[] args) throws Exception {
InputStream is = null;
FilterInputStream fis = null;
int i = 0;
char c;
try {
//create input streams
is = new FileInputStream("C://test.txt");
fis = new BufferedInputStream(is);
//read till the end of the stream
while((i = fis.read())!=-1) {
//converts integer to character
c = (char)i;
//prints
System.out.println("Character read: "+c);
}
} catch(IOException e) {
//if any I/O error occurs
e.printStackTrace();
} finally {
//releases any system resources associated with the stream
if(is!=null)
is.close();
if(fis!=null)
fis.close();
}
}
}
テキストファイル* c:/test.txt*があり、次の内容があるとします。 このファイルは、サンプルプログラムの入力として使用されます-
ABCDEF
上記のプログラムをコンパイルして実行すると、次の結果が生成されます-
Character read: A
Character read: B
Character read: C
Character read: D
Character read: E
Character read: F