Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีแปลง String เป็น InputStream Object ใน Java


ByteArrayInputStream เป็นคลาสย่อยของ InputStream มี internal buffer เก็บ bytes ที่อ่านได้จากสตรีม สามารถแปลง String เป็น InputStream ได้ด้วย ByteArrayInputStream Constructor รับ byte array ของสตริง ซึ่งได้จากการเรียก getBytes() ของ String class

ตัวอย่าง

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