欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

将输入流InputStream转换为String

程序员文章站 2022-04-23 21:35:03
...

InputStream转换为String

  /**
     * @author Administrator
     * @param InputStream
     * InputStream to String 
     */
    public  static String convertStreamToString(InputStream is) {      
         BufferedReader reader = new BufferedReader(new InputStreamReader(is));      
         StringBuilder sb = new StringBuilder();      
     
         String line = null;      
        try {      
            while ((line = reader.readLine()) != null) {      
                 sb.append(line + "\n");      
             }      
         } catch (IOException e) {      
             e.printStackTrace();      
         } finally {      
            try {      
                 is.close();      
             } catch (IOException e) {      
                 e.printStackTrace();      
             }      
         }      
     
        return sb.toString();      
     }

 也可以使用apache的io包 用来转换InputStream到String,代码示例如下

 

 

import org.apache.commons.io.IOUtils; 
public static String InputStreamToString(InputStream in){
    	String str = null;
		try {
			str = IOUtils.toString(in, "UTF-8");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	return str;
    }