1. 程式人生 > >inputStream 轉為String 類庫,不亂碼

inputStream 轉為String 類庫,不亂碼

package com.example.showhtmlorg.Utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class StreamTool {
	
	public static String toString(InputStream is) {
		
		try {
			ByteArrayOutputStream boa=new ByteArrayOutputStream();
			int len=0;
			byte[] buffer=new byte[1024];
			
			while((len=is.read(buffer))!=-1){
				boa.write(buffer,0,len);
			}
			is.close();
			boa.close();
			byte[] result=boa.toByteArray();
			
			String temp=new String(result);
			
//識別編碼
			if(temp.contains("utf-8")){
				return new String(result,"utf-8");
			}else if(temp.contains("gb2312")){
				return new String(result,"gb2312");
			}else{
				return new String(result,"utf-8");
			}
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
	}
	
	
	

}