StringReader类是一个字符输入流,用于读取字符数组和字符串。可以通过以下步骤来使用StringReader类:
import java.io.StringReader;
String input = "Hello World";
StringReader reader = new StringReader(input);
int data = reader.read();
while (data != -1) {
// 处理读取的字符
char c = (char) data;
System.out.print(c);
data = reader.read();
}
reader.close();
完整的示例代码如下:
import java.io.StringReader;
public class Main {
public static void main(String[] args) {
String input = "Hello World";
StringReader reader = new StringReader(input);
try {
int data = reader.read();
while (data != -1) {
char c = (char) data;
System.out.print(c);
data = reader.read();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
reader.close();
}
}
}
运行以上示例代码,将输出 “Hello World”。