java怎么把普通字符串转换为base64字符串

如题所述

// JUnit Test
public static void main(String[] args){
String s = "xyzXYZ";
System.out.println("The base64 encode string value is " + base64Encode(s));
System.out.println("The base64 decode string value is " + base64Decode(base64Encode(s)));
}
// 编码
public static String base64Encode(String token) {
byte[] encodedBytes = java.util.Base64.getEncoder().encode(token.getBytes());
return new String(encodedBytes,java.nio.charset.Charset.forName("UTF-8"));
}
// 解码
public static String base64Decode(String token) {
byte[] decodedBytes = java.util.Base64.getDecoder().decode(token.getBytes());
return new String(decodedBytes, java.nio.charset.Charset.forName("UTF-8"));
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-09-22
import java.io.IOException;

public class Test {

/**
* 编码
* @param bstr
* @return String
*/
public static String encode(byte[] bstr){
return new sun.misc.BASE64Encoder().encode(bstr);
}

/**
* 解码
* @param str
* @return string
*/
public static byte[] decode(String str){
byte[] bt = null;
try {
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
bt = decoder.decodeBuffer( str );
} catch (IOException e) {
e.printStackTrace();
}

return bt;
}

/**
* @param args
*/
public static void main(String[] args) {
test te = new test();
String aa = "更多更多";
aa = te.encode(aa.getBytes());
System.out.println("----aa:"+aa);
String str = aa;
String str2 = new String(te.decode(str));
System.out.println("-----str2:"+str2);
}
}本回答被提问者采纳
相似回答