📜  Java I/O-InputStreamReader

📅  最后修改于: 2020-09-27 07:21:56             🧑  作者: Mango

Java InputStreamReader

InputStreamReader是从字节流到字符流的桥梁:它读取字节,并使用指定的字符集将其解码为字符。它使用的字符集可以按名称指定,也可以显式指定,也可以接受平台的默认字符集。

建设者

Constructor name Description
InputStreamReader(InputStream in) It creates an InputStreamReader that uses the default charset.
InputStreamReader(InputStream in, Charset cs) It creates an InputStreamReader that uses the given charset.
InputStreamReader(InputStream in, CharsetDecoder dec) It creates an InputStreamReader that uses the given charset decoder.
InputStreamReader(InputStream in, String charsetName) It creates an InputStreamReader that uses the named charset.

方法

Modifier and Type Method Description
void close() It closes the stream and releases any system resources associated with it.
String getEncoding() It returns the name of the character encoding being used by this stream.
int read() It reads a single character.
int read(char[] cbuf, int offset, int length) It reads characters into a portion of an array.
boolean ready() It tells whether this stream is ready to be read.

public class InputStreamReaderExample {
public static void main(String[] args) {
try  {
InputStream stream = new FileInputStream("file.txt");
Reader reader = new InputStreamReader(stream);
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

输出:

I love my country

The file.txt contains text "I love my country" the InputStreamReader 
reads Character by character from the file