Java流——String,InputStream相互转换

一. InputStream转换为String

转换的过程是:

  1. 使用FileInputStream读取文件流;
  2. 使用InputStreamReader读取FileInputStream流;
  3. 使用BufferedReader读取InputStreamReader;
  4. 每次读取一行BufferedReader,遍历。

具体代码如下:

String template="D;//test.txt";
FileInputStream fileInputStream=null;
InputStream in=null;
BufferedReader tBufferedReader=null;
StringBuffer tStringBuffer=new StringBuffer();//转换为的字符串
try {
     fileInputStream = new FileInputStream(template);
     tBufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
     String sTempOneLine = new String("");
     while ((sTempOneLine = tBufferedReader.readLine()) != null){
             tStringBuffer.append(sTempOneLine);
     } 
}catch(Exception e){
         e.printStackTrace();
} finally{
         try {
             tBufferedReader.close();
             fileInputStream.close();
         } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
        }
}
 

 二. String转换为InputStream

转换过程需要借助ByteArrayInputStream读取字符串的字节码,ByteArrayInputStream是InputStream的子类,强制转换即可。

代码如下:

String template="abcdef";
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(template.getBytes());
InputStream inputStream=(InputStream)byteArrayInputStream;

 

posted @ 2017-09-06 18:26  话·醉月  阅读(6334)  评论(0编辑  收藏  举报