java中字符串的编码解码问题
1.将字符串转换成byte数组再恢复:
byte[] getBytes(String charsetName)
String(byte[] bytes, String charsetName)
或getBytes()
String(byte[] bytes)
2.使用String sun.misc.BASE64Encode.encode(byte[] b)
byte[] String sun.misc.BASE64Decode.decodeBuffer(String str)
将字符串转换成byte[],再转换成ASCII码;恢复时做逆操作。
在字符串转换成byte[]时,尽量用byte[] getBytes(String charsetName)方法,解码时也用相同的charsetName做参数,如果都不charsetName可能会导致一些中文字符不能正确解码。
应用例子如下:
package test;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Tools
{
/**
*
* <p>Discription:Base64解码方法</p>
* @param data 要进行解码的数据
* @param encode 编码方式
* @return
* @throws IDCException
* @author:许兆光
* @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
public static String decodeBase64(String data, String encode)
{
BASE64Decoder d = new BASE64Decoder();
try
{
return new String(d.decodeBuffer(data), encode);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return encode;
}
/**
*
* <p>Discription:Base64编码方法</p>
* @param data 要进行编码的数据
* @param encode 编码方式
* @return
* @throws IDCException
* @author:
* @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
public static String encodeBase64(String data, String encode)
{
BASE64Encoder be = new BASE64Encoder();
try
{
return be.encode(data.getBytes(encode));
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
return encode;
}
/**
*
* <p>Discription:Base64编码方法</p>
* @param data 要进行编码的数据
* @param encode 编码方式
* @return
* @throws IDCException
* @author:
* @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
public static String encodeBase64WithReplace(String data, String encode)
{
BASE64Encoder be = new BASE64Encoder();
String retrunStr = "";
try
{
retrunStr = be.encode(data.getBytes(encode)).replaceAll("//+", "%2B")
.replaceAll("///", "%2F");
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
return retrunStr;
}
}
3.使用java.net.URLEncoder类和java.net.URLDecoder类
它有static方法将字符串转换成‘pplication/x-www-form-urlencoded'格式便于在网络中传播
形如:‘%20%35'。
应用例子如下
package com.ccu.bbs.tools;
import java.io.UnsupportedEncodingException;
public class Tools
{
public static String procChaosCodeURL(String chi)
{
try
{
chi = java.net.URLEncoder.encode(chi, "ISO-8859-1");//在发送给加码用的
chi = java.net.URLDecoder.decode(chi, "GBK");//接收到解码用的
}
catch (UnsupportedEncodingException e)
{
System.out.println(e.toString());
}
return chi;
}