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 @   话·醉月  阅读(6345)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示