Java-转换字符串为InputStream

Java-转换字符串为InputStream

Tags: Java

摘要

Java-转换字符串为InputStream,更多情况下是再把InputStream输出到文件,网络等地方

String转InputStream

简单例子,把字符串转换为InputStream,然后使用BufferedReader读取再打印出来。这里只是实验而已,实际可能是输出到别的地方。

package cn.javacore.io.file;

import java.io.*;

public class _29_StringToInputStreamExample {
    public static void main(String[] args) throws IOException {
        String str = "This is a String ~ GoGoGo";

        // convert String into InputStream
        InputStream is = new ByteArrayInputStream(str.getBytes());

        // read it with BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        br.close();
    }
}