运行环境:
开发工具:IntelliJ IDEA 2017.1.4
开发环境:JDK1.8、Maven3.5.0等(其他没啥影响的就不列举了)
步骤:
1、在pom.xml添加依赖
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
这里用的是Apache的Commons Codec工具包,一款很好用的工具包,除了base64还有别的用法,具体可以自行去看API,这里不赘述。
2、在代码中使用
public class HelloWorld {
public static void main(String []args) {
//转换前的字符串
String beforeStr = "abcdefg";
//转换后的字符串
String afterStr = Base64.encodeBase64String(beforeStr.getBytes());
//解密后的字符串
String recoverStr = Base64.decodeBase64(afterStr);
}
}
上面代码是在插入代码的时候现写的,所以没加包,所以需要注意的一点,导包的时候要注意,因为Base64的相关包是挺多的
导入的包是 import org.apache.commons.codec.binary.Base64;