解決InputStream轉化String亂碼問題

    //bug,中文爲亂碼
    //InputStream轉String
    public String inputStream2String(InputStream in) throws IOException {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1;) {
            out.append(new String(b, 0, n));
        }
        return out.toString();
    }


    // 解決 InputStream 轉化 String 亂碼問題
    public String inputStream2StringNew(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;
        }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章