Java.io.Reader
Reader
字段:
- protected Object lock – 这是用于同步针对此流的操作的对象。
构造函数 | 描述 |
---|---|
protected Reader() | 创建一个字符流reader,其关键部分将在读取器本身上同步 |
protected Reader(Object lock) | 创建一个字符流reader,其临界区将同步给定对象。 |
方法
方法 | 说明 |
---|---|
void close() | 关闭该流并释放与之关联的所有系统资源 |
void mark(int readAheadLimit) | 标记流中的当前位置。 |
boolean markSupported() | 否支持mark()操作。 |
int read() | 读取单个字符。 |
int read(char[] b, int off, int len) | 读取字符到数组的一部分。 |
boolean ready() | 是否已准备好被读取。 |
void reset() | 重置流至最新的标记,如果没有被标记从头开始。 |
long skip(long n) | 跳过n个字符。 |
abstract void close()
关闭该流并释放与之关联的所有系统资源
@Test
void ReaderClose() {
String s = "Hello World";
// create a new StringReader
Reader reader = new StringReader(s);
// read the first five chars
try {
for (int i = 0; i < 5; i++) {
char c = (char) reader.read();
System.out.print(c);
}
// change line
System.out.println();
// close the stream
System.out.println("Closing Stream...");
reader.close();
System.out.println("Stream Closed.");
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void mark(int readAheadLimit)
标记流中的当前位置。readAheadLimit 表示在标记失效前可读到的字符串数限制
public void reset()
重置流。如果流已被标记,然后尝试进行定位标记
@Test
void ReaderMark() {
try {
String s = "Hello World";
// create a new StringReader
Reader reader = new StringReader(s);
// read the first five chars
for (int i = 0; i < 5; i++) {
char c = (char) reader.read();
System.out.print(c);
}
// mark current position for maximum of 10 characters
reader.mark(10);
// change line
System.out.println();
// read five more chars
for (int i = 0; i < 6; i++) {
char c = (char) reader.read();
System.out.print(c);
}
// reset back to the marked position
reader.reset();
// change line
System.out.println();
// read six more chars
for (int i = 0; i < 6; i++) {
char c = (char) reader.read();
System.out.print(c);
}
// close the stream
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public boolean markSupported()
判断此流是否支持mark()操作
@Test
void ReaderMarkSupported() {
String s = "Hello World";
// create a new StringReader
Reader reader = new StringReader(s);
try {
// read the first five chars
for (int i = 0; i < 5; i++) {
char c = (char) reader.read();
System.out.print(c);
}
// change line
System.out.println();
// check if mark is supported
System.out.println(reader.markSupported());
// close the stream
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public int read()
读取单个字符
@Test
void ReaderRead() {
String s = "Hello World";