Dưới đây là ví dụ đơn giản chuyển String thành InputStream trong Java. Sau khi chuyển xong sẽ dùng BufferedReader để đọc và hiển thị dữ liệu từ InputStream.
Ví dụ chuyển String thành InputStream
package com.ngockhuong;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class StringToInputStreamExample {
public static void main(String[] args) throws IOException {
String str = "Nội dung String bạn muốn chuyển";
// chuyển String thành InputStream
InputStream is = new ByteArrayInputStream(str.getBytes());
// đọc nội dung với BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}