您可以将属性编码为 Base64。唯一的限制是您的属性必须具有固定大小。您可能希望对编码字符串应用 MD5 算法或类似算法。
看看这个使用apache commons codec for java 1.4的snipplet
public class Base64Encoder {
/**
* Base64 game properties encoded
* @param properties list of properties as Strings
* @return base64 encoded properties
*/
public String encodeProperties(List properties){
StringBuffer buffer = new StringBuffer();
Iterator iter = properties.iterator();
while(iter.hasNext()){
buffer.append(iter.next().toString());
}
return Base64.encodeBase64String(buffer.toString().getBytes());
}
/**
* Decodes a based64 properties
* @param propertiesSize list of Integer with each property size
* @param encodedProperties base64 encoded properties
* @return List of properties as String
*/
public List decodeProperties(List propertiesSize, String encodedProperties){
List decodedProperties = new ArrayList();
Iterator iter = propertiesSize.iterator();
String decoded = new String(Base64.decodeBase64(encodedProperties.getBytes()));
int current = 0;
while(iter.hasNext()){
Integer propertySize = new Integer(iter.next().toString());
String property = decoded.substring(current, current + propertySize.intValue());
decodedProperties.add(property);
current += propertySize.intValue();
}
return decodedProperties;
}
public static void main(String[] args){
String points = "1450";
String level = "12";
String lifes = "2";
Base64Encoder encoder = new Base64Encoder();
List properties = new ArrayList();
properties.add(points);
properties.add(level);
properties.add(lifes);
String encodedProperties = encoder.encodeProperties(properties); //MTQ1MDEyMg==
System.out.println(encodedProperties);
List propertiesSize = new ArrayList();
propertiesSize.add(Integer.valueOf(points.length()));
propertiesSize.add(Integer.valueOf(level.length()));
propertiesSize.add(Integer.valueOf(lifes.length()));
System.out.println(encoder.decodeProperties(propertiesSize, encodedProperties)); //[1450, 12, 2]
}
}