zoukankan      html  css  js  c++  java
  • 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();
    }

  • 相关阅读:
    Bitstream or PCM?
    centos7安装Redis-3.2.8
    【生肉】【不义联盟
    ES6中Map数据结构学习笔记
    机器学习基石入门
    2019/5/9 长难句
    文件遍历选取脚本
    [JS奇怪的世界]No.55 危險小叮嚀:陣列與for in
    OpenGL Panorama Player
    吴裕雄--天生自然MySQL学习笔记:MySQL 连接
  • 原文地址:https://www.cnblogs.com/ITEagle/p/2088719.html
Copyright © 2011-2022 走看看