3
回答
Java的UTF-8转GBK,都说简单,但就是不对
Properties initProp = new Properties(System.getProperties());
		System.out.println("file.encoding:"
				+ initProp.getProperty("file.encoding"));
tranData = "1234qwer我的";
		System.out.println(tranData);
		try {
			tranData=new String(tranData.getBytes(),"gbk");
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
String tranData64 = Base64Encode(tranData.getBytes());
		System.out.println(tranData64);

public static String Base64Encode(byte[] content){
		return new sun.misc.BASE64Encoder().encode(content);    
	}

右键,文件属性是UTF-8,看系统属性也是UTF-8,数据直接写死。但转为GBK后,求base64编码错误。

1234qwer我的

编码后正确的结果应该是 

MTIzNHF3ZXLO0rXE

好吧,很多人都觉得简单,开始我也觉得,但无论怎么试和修改,就是的不出正确结果。谁能写出一段Java代码,得出这个结果

在线验证:http://www.so.com/s?psid=1741b0f5e00136c1aaf40563332aaaee&q=base64%E5%9C%A8%E7%BA%BF%E8%A7%A3%E7%A0%81&pq=java+%E7%BC%96%E7%A0%81%E8%BD%AC%E6%8D%A2+ISO8859-1&src=srp_suggst_s_3.0&fr=360chrome_newtab_search#

举报
共有3个答案 最后回答: 3年前

已解决。答案如下,大家参考下

public static void main(String[] args) throws UnsupportedEncodingException {
		String tranData0 = "1234qwer我的";
 String tranData640 = ProcessMessage.Base64Encode(tranData0.getBytes());
 System.out.println("UTF-8的:"+tranData640);
 
 String tranData = "1234qwer我的";
 tranData=new String(tranData.getBytes("utf-8"),"gbk");
 String tranData64 = ProcessMessage.Base64Encode(tranData.getBytes());
 System.out.println("错误的:"+tranData64);
 
 String tranData3 = "1234qwer我的";
 tranData=new String(tranData3.getBytes("utf-8"),"gbk");
 String tranData643 = ProcessMessage.Base64Encode(tranData.getBytes("GBK"));
 System.out.println("也是错误的:"+tranData643);
 
 String tranData2 = "1234qwer我的";
 tranData=new String(tranData2.getBytes("utf-8"));
 String tranData642 = ProcessMessage.Base64Encode(tranData.getBytes("GBK"));
 System.out.println("正确的:"+tranData642);

	}



再来一个GBK转UTF-8编码的,看看你能猜对不?

public class CodeTest {
	public static void main(String[] args) throws UnsupportedEncodingException {
		String tranData0 = "1234qwer我的";
		String tranData640 = Base64Encode(tranData0.getBytes());
		System.out.println("GBK的:"+tranData640);
		
		String tranData = "1234qwer我的";
		tranData=new String(tranData.getBytes("gbk"),"UTF-8");
		String tranData64 = Base64Encode(tranData.getBytes());
		System.out.println("我TM什么都不是:"+tranData64);
		
		String tranData3 = "1234qwer我的";
		tranData3=new String(tranData3.getBytes("utf-8"),"gbk");
		String tranData643 = Base64Encode(tranData3.getBytes("GBK"));
		System.out.println("你以为是GBK,但实际是utf-8的:"+tranData643);
		
		String tranData2 = "1234qwer我的";
//		tranData=new String(tranData2.getBytes("utf-8"));
		String tranData642 = Base64Encode(tranData2.getBytes("UTF-8"));
		System.out.println("utf-8的:"+tranData642);
	}
	
	public static String Base64Encode(byte[] content){
		return new sun.misc.BASE64Encoder().encode(content);    
	}

}



顶部