JAVA中3種將byte轉換為String的方法

來源:互聯網
上載者:User

原文地址:http://www.cnblogs.com/521shina/archive/2009/03/19/1417204.html

HttpClient 類庫中GetMethod類的getResponseBody方法返回的是byte[]類型,要操作起來不方便,我想把它轉化成String類型。

查了網上的資料,有說法認為用這種方法比較好
BASE64Encoder enc=new BASE64Encoder();
String 轉換後的string=enc.encode(byte數組);

參考http://hi.baidu.com/zhaolm/blog/item/397b0808bc6023d362d986f3.html/cmtid/e3a206f43cb6f9e87609d746

但是有的人說這種

BASE64Encoder是非官方JDK裡面的類。雖然可以在JDK裡能找到並使用,但是在API裡查不到。這兩個可能是SUN公司內部人使用的。SUN開頭的包裡面的類都找不到相關文檔,所以裡面可能都是非官方的類。出現警告也是非常合理和正常的,因為以後SUN可能會更新或這刪除那些非官方的類,建議不要使用。

有這個缺點,又要匯入jar包,挺麻煩的,所以就放棄採用它了。

於是又查了一個英文網站上說了3個方法,都比較簡單。我用了第3種,目前看沒什麼問題。

摘自http://www.javadb.com/convert-byte-to-string

/** * * @author javadb.com */public class Main {        /**     * Example method for converting a byte to a String.     */    public void convertByteToString() {                byte b = 65;                //Using the static toString method of the Byte class        System.out.println(Byte.toString(b));        //Using simple concatenation with an empty String        System.out.println(b + "");                //Creating a byte array and passing it to the String constructor        System.out.println(new String(new byte[] {b}));            }        /**     * @param args the command line arguments     */    public static void main(String[] args) {        new Main().convertByteToString();    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.