String与byte[]互转

String与byte[]互转,每次用,每次查,觉得还是总结一下,加深记忆比较好,看代码一看便知:
import java.io.UnsupportedEncodingException;

public class StringByteTest{
    public static void main(String[] args){
        // change String to bytes
        String hello = "hello";
        byte[] helloBytes = hello.getBytes();
        System.out.println("helloBytes:" + helloBytes);

        // change bytes to String
        String str = new String(helloBytes);
        System.out.println("str:" + str);

        // set special encode
        try {
            String str2 = new String(helloBytes, "UTF-8");
            System.out.println("str2:" + str2);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (helloBytes != null && helloBytes.length > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (byte b : helloBytes) {
                // 以十六进制输出
                stringBuilder.append(String.format("%X", b));
            }
            System.out.println("hello hex:" + stringBuilder);
        }

    }
}
结果:

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值