Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách chuyển đổi String thành InputStream object trong Java?

ByteArrayInputStream là subclass của InputStream chứa buffer nội bộ lưu bytes có thể đọc từ stream. Chuyển String thành InputStream bằng ByteArrayInputStream. Constructor nhận mảng byte của chuỗi, lấy bằng getBytes() của String.

Ví dụ

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)); 
    } 
}

Kết quả

Welcome to TutorialsPoint