java怎么把普通字符串转换为base64字符串
发布网友
发布时间:2022-04-21 15:26
我来回答
共2个回答
热心网友
时间:2022-04-13 01:01
// 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"));
}
热心网友
时间:2022-04-13 02:19
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);
}
}