📜  Java IO-StringReader类(1)

📅  最后修改于: 2023-12-03 15:01:30.786000             🧑  作者: Mango

Java IO-StringReader类

简介

StringReader类是Java IO包中提供的一个类,用于读取一个字符串并将其转换成Reader流。

构造方法
public StringReader(String str)

该构造方法接受一个字符串参数,用于创建一个新的StringReader对象。

方法
read()
public int read() throws IOException

该方法用于读取一个字符并返回其对应的整数值。如果已经读取到字符串的末尾,返回-1。

read(char[] cbuf, int off, int len)
public int read(char[] cbuf, int off, int len) throws IOException

该方法用于读取指定长度字符并将其存储到字符数组中,同时返回实际读取的字符数。如果已经读取到字符串的末尾,返回-1。

skip(long n)
public long skip(long n) throws IOException

该方法用于跳过指定长度的字符。

ready()
public boolean ready() throws IOException

该方法用于判断输入流是否准备好被读取。

mark(int readAheadLimit)
public void mark(int readAheadLimit) throws IOException

该方法用于标记此流的当前位置。

reset()
public void reset() throws IOException

该方法用于将流重置为最近标记的位置。

close()
public void close() throws IOException

该方法用于关闭流并释放与其相关的任何系统资源。

使用示例
String str = "Hello world!";
StringReader reader = new StringReader(str);
int i = reader.read();
while(i != -1) {
    System.out.print((char) i);
    i = reader.read();
}
reader.close();

输出:

Hello world!
总结

StringReader类是Java IO包提供的一个类,用于读取字符串并转换成Reader流。它可以方便地处理字符串读取和分析,同时提供了一系列有用的方法。