栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 中InputStream,String,File之间的相互转化对比

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 中InputStream,String,File之间的相互转化对比

InputStream,String,File相互转化

 1. String --> InputStream

InputStream String2InputStream(String str){
 ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes());
 return stream;
}

2. InputStream --> String

String inputStream2String(InputStream is){
 BufferedReader in = new BufferedReader(new InputStreamReader(is));
 StringBuffer buffer = new StringBuffer();
 String line = "";
 while ((line = in.readLine()) != null){
  buffer.append(line);
 }
 return buffer.toString();
}

今天从网上看到了另一种方法,特拿来分享

String all_content=null;
  try {
  all_content =new String();

   InputStream ins = 获取的输入流;

   ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
  byte[] str_b = new byte[1024];
  int i = -1;
  while ((i=ins.read(str_b)) > 0) {
   outputstream.write(str_b,0,i);
  }
  all_content = outputstream.toString();
 } catch (Exception e) {

e.printStackTrace();
  }

此两种方法上面一种更快,但是比较耗内存,后者速度慢,耗资源少

3、File --> InputStream

InputStream in = new InputStream(new FileInputStream(File));

4、InputStream --> File

public void inputstreamtofile(InputStream ins,File file){
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/146927.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号