Java 8——Base64工具

在java 8之前如果需要使用base64编解码,必须使用三方库,如:apache的commons-codec。

但是java 8将base64编解码的工具引入进来:

public class TestBase64 {

    public static void main(String[] args) {
        String plainTxt = "i love you!";
        String secure = base64Encode(plainTxt);
        base64Decode(secure);
    }


    public static String base64Encode(String plainTxt) {
        byte[] bytes = Base64.getEncoder().encode(plainTxt.getBytes());
        String secureTxt = new String(bytes);
        System.out.println(secureTxt);
        return secureTxt;
    }

    public static void base64Decode(String secureTxt) {
        byte[] bytes = Base64.getDecoder().decode(secureTxt.getBytes());
        String plainTxt = new String(bytes);
        System.out.println(plainTxt);
    }
}

执行结果:

aSBsb3ZlIHlvdSE=
i love you!
参考

What's New in JDK 8

posted @ 2018-08-08 15:13  怀瑾握瑜XI  阅读(582)  评论(0编辑  收藏  举报