ByteArrayInputStream เป็นคลาสย่อยของ InputStream คลาสและประกอบด้วยบัฟเฟอร์ภายในที่มี ไบต์ ที่สามารถอ่านได้จากกระแส เราสามารถแปลง สตริงเป็น InputStream วัตถุโดยใช้ ByteArrayInputStream ระดับ. ตัวสร้างคลาสนี้ใช้อาร์เรย์สตริงไบต์ซึ่งสามารถทำได้โดยการเรียก getBytes() เมธอดของคลาสสตริง
ตัวอย่าง
import java.io.*;
public class StringToInputStreamTest {
public static void main(String []args) throws Exception {
String str = "Welcome to TutorialsPoint";
InputStream input = getInputStream(str, "UTF-8");
int i;
while ((i = input.read()) > -1) {
System.out.print((char) i);
}
System.out.println();
}
public static InputStream getInputStream(String str, String encoding) throws UnsupportedEncodingException {
return new ByteArrayInputStream(str.getBytes(encoding));
}
} ผลลัพธ์
Welcome to TutorialsPoint