📜  Java I/O-reader类

📅  最后修改于: 2020-09-27 04:45:17             🧑  作者: Mango

Java reader

Java Reader是用于读取字符流的抽象类。子类必须实现的唯一方法是read(char [],int,int)和close()。但是,大多数子类将覆盖某些方法,以提供更高的效率和/或附加功能。

一些实现类是BufferedReader,CharArrayReader,FilterReader,InputStreamReader,PipedReader,StringReader

领域

Modifier and Type Field Description
protected Object lock The object used to synchronize operations on this stream.

建设者

Modifier Constructor Description
protected Reader() It creates a new character-stream reader whose critical sections will synchronize on the reader itself.
protected Reader(Object lock) It creates a new character-stream reader whose critical sections will synchronize on the given object.

方法

voidreset()It resets the stream.

Modifier and Type Method Description
abstract void close() It closes the stream and releases any system resources associated with it.
void mark(int readAheadLimit) It marks the present position in the stream.
boolean markSupported() It tells whether this stream supports the mark() operation.
int read() It reads a single character.
int read(char[] cbuf) It reads characters into an array.
abstract int read(char[] cbuf, int off, int len) It reads characters into a portion of an array.
int read(CharBuffer target) It attempts to read characters into the specified character buffer.
boolean ready() It tells whether this stream is ready to be read.
long skip(long n) It skips characters.

import java.io.*;
public class ReaderExample {
public static void main(String[] args) {
try {
Reader reader = new FileReader("file.txt");
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
            reader.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}

file.txt:

I love my country

输出:

I love my country