---
title: "JAVA将字符串变为输入流"
author: "zben000"
date: "2010-10-18T15:56:22Z"
tags: ["Java"]
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2010-10-18T15:56:22Z"
id: 787562
url: "https://zben000.iteye.com/blog/787562"
---

JAVA将字符串变为输入流
关于字符串转化为输入流，我找到2种方法：
用StringReader将字符串转化为Reader 
用ByteArrayInputStream将字符串转化为InputStream. 还有一个类StringBufferInputStream也可以将String转化为InputStream，但是由于它只支持字符串中每个字符的低八位，所以已经被遗弃了。
PS: java.io.Reader 和 java.io.InputStream 组成了 Java 输入类。Reader 用于读入16位字符，也就是 Unicode 编码的字符；而 InputStream 用于读入 ASCII 字符和二进制数据。

示例代码如下：

public static InputStream getStringInputStream(String s) {
    if (s != null && !s.equals("")) {
        try { 

            ByteArrayInputStream stringInputStream = new ByteArrayInputStream(
                    s.getBytes());
            return stringInputStream;
        } catch (Exception e) { 

            e.printStackTrace();
        }
    }
    return null;
} 

public static Reader getStringReader(String s) {
    if (s != null && !s.equals("")) {
        try { 

            StringReader stringReader = new StringReader(s);
            return stringReader;
        } catch (Exception e) { 

            e.printStackTrace();
        }
    }
    return null;
}
