在本教程中,我们将借助示例学习Java StringReader及其方法。
java.io包的StringReader类可用于从字符串读取数据(以字符为单位)。
它继承了抽象类Reader。

注意:在StringReader中,指定的字符串充当源,从其中分别读取字符。
为了创建一个StringReader,我们必须首先导入java.io.StringReader包。导入包后,就可以创建字符串读取器了。
//创建 StringReader StringReader input = new StringReader(String data);
在这里,我们创建了一个StringReader,它从指定的名为data的字符串中读取字符。
StringReader类为Reader类中的不同方法提供了实现。
read() - 从字符串读取器读取单个字符
read(char[] array) - 从阅读器读取字符并将其存储在指定的数组中
read(char[] array, int start, int length) - 从阅读器读取等于length字符的数量,并从start位置开始存储在指定的数组中
import java.io.StringReader;
public class Main {
  public static void main(String[] args) {
    String data = "This is the text read from StringReader.";
    //创建一个字符数组
    char[] array = new char[100];
    try {
      //创建一个StringReader
      StringReader input = new StringReader(data);
      //使用read方法
      input.read(array);
      System.out.println("从字符串读取数据:");
      System.out.println(array);
      input.close();
    }
    catch(Exception e) {
      e.getStackTrace();
    }
  }
}输出结果
从字符串读取数据: This is the text read from StringReader.
在上面的示例中,我们创建了一个名为input的字符串读取器。 字符串阅读器链接到字符串数据(data)。
String data = "This is a text in the string."; StringReader input = new StringReader(data);
为了从字符串中读取数据,我们使用了read()方法。
在此,该方法从阅读器读取字符数组,并将其存储在指定的数组中。
要丢弃和跳过指定数量的字符,可以使用skip()方法。例如
import java.io.StringReader;
public class Main {
  public static void main(String[] args) {
    String data = "This is the text read from StringReader";
    System.out.println("原始数据: " + data);
    //创建一个字符数组
    char[] array = new char[100];
    try {
      //创建 StringReader
      StringReader input = new StringReader(data);
      //使用 skip() 方法
      input.skip(5);
      //使用 read 方法
      input.read(array);
      System.out.println("跳过5个字符后的数据:");
      System.out.println(array);
      input.close();
    }
    catch(Exception e) {
      e.getStackTrace();
    }
  }
}输出结果
原始数据: This is the text read from the StringReader 跳过5个字符后的数据: is the text read from the StringReader
在上面的示例中,我们使用skip()方法从字符串读取器中跳过5个字符。因此,字符'T'、'h'、'i'、's'和' '从原始字符串读取器中被跳过。
要关闭字符串阅读器,我们可以使用该close()方法。调用close()方法后,我们将无法使用读取器从字符串读取数据。
| 方法 | 描述 | 
|---|---|
| ready() | 检查字符串读取器是否准备好被读取 | 
| mark() | 标记读取器中已读取数据的位置 | 
| reset() | 重置标记,返回到阅读器中设置标记的位置 |