美文网首页
java inputStream转String简记

java inputStream转String简记

作者: WeakRefrence | 来源:发表于2017-01-20 14:43 被阅读0次
    1.(StringBuffer+InputStreamReader+BufferedReader ),不推荐使用,BufferedReader在readLine() 时会在读取到换行符时直接返回,然后读取下一行,会丢失换行符(what fk is that?)。
    public String inputStreamString (InputStream in) throws IOException {
      String tempLine="";
      StringBuffer resultBuffer = new StringBuffer();
      InputStreamReader inputStreamReader = new InputStreamReader(in);
      BufferedReader reader = new BufferedReader(inputStreamReader);
      while ((tempLine = reader.readLine()) != null) {
        resultBuffer.append(tempLine);
      }
      return  resultBuffer.toString();
    }
    
    2.(ByteArrayOutputStream)推荐使用
    public String intputStreamString2(InputStream inputStream){
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int i=-1;
      try {
        while((i=inputStream.read())!=-1){
          baos.write(i);
        }
        return baos.toString();
      } catch (IOException e) {
        e.printStackTrace();
      }
      return "";
    }
    

    相关文章

      网友评论

          本文标题:java inputStream转String简记

          本文链接:https://www.haomeiwen.com/subject/csgwbttx.html