InputStream & String

来源:互联网 发布:西村由纪江 知乎 编辑:程序博客网 时间:2024/05/18 20:51

InputStream提供的是字节流的读取,而非文本读取,用Reader读取出来的是char数组或者String ,使用InputStream读取出来的是byte数组。
Reader类及其子类提供的字符流的读取char,inputStream及其子类提供字节流的读取byte,所以 FileReader类是将文件按字符流的方式读取,FileInputStream则按字节流的方式读取文件;InputStreamReader可以将读如stream转换成字符流方式,是reader和stream之间的桥梁。

1 . String –> Inputstream

public InputSteam getInputStreamFromString(String str){    InputSteam in=new ByteArrayInputStream(str.getBytes());}

2 . Inputstream ->String

    public static String convertStreamToString(InputStream is) {              StringBuilder sb = new StringBuilder();              String line = null;              try {            BufferedReader reader = new BufferedReader(new InputStreamReader(is));                          while ((line = reader.readLine()) != null) {                      sb.append(line);                  }           } catch (IOException e) {            e.printStackTrace();              } finally {                  try {                is.close();            } catch (IOException e) {                e.printStackTrace();            }        }        return sb.toString();          }
原创粉丝点击