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”。