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

InputStream,String,File相互转化

创新互联公司是一家网站建设、成都做网站,提供网页设计,网站设计,网站制作,建网站,按需开发,网站开发公司,于2013年成立是互联行业建设者,服务者。以提升客户品牌价值为核心业务,全程参与项目的网站策划设计制作,前端开发,后台程序制作以及后期项目运营并提出专业建议和思路。

 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();
}

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


网页题目:java中InputStream,String,File之间的相互转化对比
URL地址:http://bzwzjz.com/article/gcdgjd.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: 成都网站建设 网站制作 重庆网站建设 网站制作报价 app网站建设 成都响应式网站建设 成都网站设计 成都网站设计 网站建设费用 手机网站建设套餐 成都网站建设 成都网站设计 宜宾网站设计 成都做网站建设公司 商城网站建设 重庆企业网站建设 成都网站建设 四川成都网站建设 做网站设计 定制网站建设多少钱 外贸营销网站建设 成都网站建设推广