博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
11.通用数据结构,并解析和生成(界限计划2)
阅读量:5121 次
发布时间:2019-06-13

本文共 66312 字,大约阅读时间需要 221 分钟。

如果每个不同的结构都要写一个对象做映射,那么会累死人的,所以我做了一个通用类,来写数据

类的结构为

每个子类的结构类似为以下,包含100个对象

其中第一个为非list的原因为概括类,不重复,剩下的都有可能重复,也可能没有

总的思路为:

加载

1.加载bin,把他的byte处理为string对象

2.依据规则处理string对象为通用类

解析

1.解析通用类反处理为string对象

2.把通用类处理为byte并生成对应文件

package code;import java.io.DataOutputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import code.dao.FileByte;public class Main {        public static void main(String[] args) {        byte[] rsbt=null;        StringBuilder buf = new StringBuilder();        int s;        byte[] ctbt=null;        FileByte out=new FileByte();        {
//读取bin生成string try { rsbt = ComUtil.readFile(Config.Btls.WC4_BTL);//"D:\\test1.bin" } catch (IOException e) { e.printStackTrace(); } for (byte d : rsbt) { buf.append(String.format("%02x", d)); } } {
//解析stirng for(s=0;s<(int)(buf.length()/2);s++) { try { out.writeByte(Integer.parseInt(buf.substring(s*2, (s+1)*2),16)); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } FileOutputStream fs; try { fs = new FileOutputStream("D://wc4Test.btl"); fs.write(out.getByte()); fs.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
总思路

以下为全部代码

package code;import java.io.DataOutputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.JSONObject;import code.dao.BTLDAO;import code.dao.DefRule;import code.dao.FileByte;import code.dao.module.BtlModule0;import code.dao.module.BtlModule1;import code.dao.module.BtlModule10;import code.dao.module.BtlModule11;import code.dao.module.BtlModule12;import code.dao.module.BtlModule13;import code.dao.module.BtlModule14;import code.dao.module.BtlModule15;import code.dao.module.BtlModule16;import code.dao.module.BtlModule17;import code.dao.module.BtlModule18;import code.dao.module.BtlModule19;import code.dao.module.BtlModule2;import code.dao.module.BtlModule20;import code.dao.module.BtlModule3;import code.dao.module.BtlModule4;import code.dao.module.BtlModule5;import code.dao.module.BtlModule6;import code.dao.module.BtlModule7;import code.dao.module.BtlModule8;import code.dao.module.BtlModule9;public class BTLTooL {    //读取通用btl,以及相关处理    public static void main(String[] args) {        BTLDAO binFile = null;        Map
rsMap = null; String rule = Config.Rules.WC4_RULE; String btl = Config.Btls.WC4_BTL; try { binFile = LoadBtl(rule,btl); } catch (Exception e) { e.printStackTrace(); } try { rsMap = getBtlMap(rule,binFile); } catch (Exception e) { e.printStackTrace(); } saveMapBin(rule, rsMap, "D://wc4Test.btl"); System.out.println("ok"); } //加载Btl public static BTLDAO LoadBtl(String rule,String path) throws Exception { byte[] rsbt = null; BTLDAO btl = new BTLDAO(); BtlModule0 bi; StringBuilder buf = new StringBuilder(); String cutStr = ""; int bufTag = 0; int cutSumCt = 1;//总循环次数 int mapW = 0, mapH = 0, i; JSONObject row; List
rs; Map rsMap = null; Map biMap = null; {
//读取bin try { rsbt = ComUtil.readFile(path);//"D:\\test1.bin" } catch (IOException e) { e.printStackTrace(); } int line = 0;// 十六进制标记 for (byte d : rsbt) { if (line % 1 == 0) { buf.append(String.format("%02x", d)); // System.out.println(String.format("%02x", d)); } } } { //得到基础信息 cutStr = "bm0"; row = getInfoByRootName(rule, cutStr); rs = getDefRuleInfosByRow(row); bi = new BtlModule0(); rsMap = cutBtl(rs, bi, buf, bufTag, cutSumCt); bi = (BtlModule0) rsMap.get("T"); btl.setBm0(bi); bufTag = Integer.parseInt(rsMap.get("bufTag").toString()); biMap = ComUtil.ConvertObjToMap(bi); for (i = 0; i < rs.size(); i++) { if (rs.get(i).getFunction().toString().equals("mapH")) { mapH = Integer.parseInt(biMap.get(rs.get(i).getId()).toString()); } if (rs.get(i).getFunction().toString().equals("mapW")) { mapW = Integer.parseInt(biMap.get(rs.get(i).getId()).toString()); } } if (mapW * mapH == 0) { throw new Exception("没有得到有效的宽高"); } } { //重复读取所有基本信息 Object[] objects = new Object[] { (new BtlModule1()), (new BtlModule2()), (new BtlModule3()), (new BtlModule4()), (new BtlModule5()), (new BtlModule6()), (new BtlModule7()), (new BtlModule8()), (new BtlModule9()), (new BtlModule10()), (new BtlModule11()), (new BtlModule12()), (new BtlModule13()), (new BtlModule14()), (new BtlModule15()), (new BtlModule16()), (new BtlModule17()), (new BtlModule18()), (new BtlModule19()), (new BtlModule20()) }; String[] cutStrs = new String[] { "bm1", "bm2", "bm3", "bm4", "bm5", "bm6", "bm7", "bm8", "bm9", "bm10", "bm11", "bm12", "bm13", "bm14", "bm15", "bm16", "bm17", "bm18", "bm19", "bm20" }; for (i = 0; i < objects.length; i++) { row = getInfoByRootName(rule, cutStrs[i]); rs = getDefRuleInfosByRow(row); if (row.getBoolean("ifCycle")) { if (row.getString("Count").equals("one")) { cutSumCt = 1; } else if (row.getString("Count").equals("sumGride")) { cutSumCt = mapW * mapH; } else { if (biMap.get(row.getString("Count")) != null) { cutSumCt = Integer.parseInt((String) biMap.get(row.getString("Count"))); } else { cutSumCt = 0; } } } else { cutSumCt = 1; } rsMap = cutBtl(rs, objects[i], buf, bufTag, cutSumCt); ComUtil.setVal(btl, "set" + ComUtil.UpperInitial(cutStrs[i]), rsMap.get("T")); bufTag = Integer.parseInt(rsMap.get("bufTag").toString()); } } return btl; } //从主节点获取信息 public static JSONObject getInfoByRootName(String path, String rootName) { List
defRules = new ArrayList
(); DefRule defRule; JSONObject obj = ComUtil.XmlRead(path); JSONArray array = obj.getJSONArray("attribute"); JSONObject row = null; for (int i = 0; i < array.size(); i++) { row = array.getJSONObject(i); if (row.get("id").equals(rootName)) { return row; } } return row; } //根据pathName 来获取 List
rootName为分节点的id public static List
getDefRuleInfosByRow(JSONObject row) { List
defRules = new ArrayList
(); DefRule defRule; JSONObject row2 = null; JSONArray arraycoord = row.getJSONArray("nodeList"); ; for (int j = 0; j < arraycoord.size(); j++) { row2 = arraycoord.getJSONObject(j); defRule = new DefRule(); defRule.setName(row2.getString("name")); defRule.setSize(row2.getIntValue("size")); defRule.setType(row2.getString("type")); defRule.setRemark(row2.getString("remark")); defRule.setFunction(row2.getString("function")); defRule.setDefaul(row2.getString("defaul")); defRule.setId(row2.getString("id")); defRules.add(defRule); } return defRules; } //切割btl根据xml的记录 public static
Map
cutBtl(List
rs, T item, StringBuilder buf, int bufTag, int cycleCount) { Map
rsMap = new HashMap
(); List
ts = new ArrayList
(); Class clazz = item.getClass(); Field[] fieldName; Class clazs; Field f = null; int beginBufTag = bufTag; int cutL, c; String str = null; for (c = 0; c < cycleCount; c++) { fieldName = clazz.getDeclaredFields(); try { item = (T) clazz.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } clazs = item.getClass(); for (DefRule r : rs) { for (int i = 0; i < fieldName.length; i++) { // 创建实例 try { f = clazs.getDeclaredField(fieldName[i].getName()); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } f.setAccessible(true); if (r.getId().equals(fieldName[i].getName().toString())) { cutL = r.getSize(); //System.out.println("B:Name1:"+fieldName[i].getName()+" c:"+c+" bs:"+bufTag+"~"+(bufTag + cutL)+" v:"+buf.substring(bufTag, bufTag + cutL)); if (r.getType().equals("Byte")) { str = ComUtil.converByte(buf.substring(bufTag, bufTag + cutL)); } else if (r.getType().equals("Integer")) { str = ComUtil.converInteger(buf.substring(bufTag, bufTag + cutL)); } else if (r.getType().equals("Long")) { str = ComUtil.converLong(buf.substring(bufTag, bufTag + cutL)); } else if (r.getType().equals("Single")) { str = ComUtil.converSingle(buf.substring(bufTag, bufTag + cutL)); } else if (r.getType().equals("String")) { str = ComUtil.converString(buf.substring(bufTag, bufTag + cutL)); } else if (r.getType().equals("?")) { str = buf.substring(bufTag, bufTag + cutL); } if (c < 1) { System.out.println("id:" + r.getId() + ":" + r.getName() + " c:" + c + " size:" + cutL + " N:" + r.getRemark() + " value:" + str); } bufTag = bufTag + cutL; try { f.set(item, str); } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } } } } if (item != null) { ts.add(item); } } if (cycleCount == 1 && beginBufTag == 0) { rsMap.put("T", item); } else { ComUtil.removeNull(ts); rsMap.put("T", ts); } rsMap.put("bufTag", bufTag); return rsMap; } //写为bin数组 private static Map getBtlMap(String rule,BTLDAO binFile) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { int i; Object om; Map map = null; List
> tempMaps; Map
rsMap = new HashMap(); Object s; JSONObject row; { //遍历btl Field[] fields = binFile.getClass().getDeclaredFields();//Object是已经被赋值的对象实例 for (Field field : fields) { if (!field.isAccessible()) { field.setAccessible(true); } //如果是list类 if (List.class.isAssignableFrom(field.getType())) { Type t = field.getGenericType(); if (t instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) t; Class clz = (Class) pt.getActualTypeArguments()[0];//得到对象list中实例的类型 Class clazz = field.get(binFile).getClass();//获取到属性的值的Class对象 Method m = clazz.getDeclaredMethod("size"); int size = (Integer) m.invoke(field.get(binFile));//调用list的size方法,得到list的长度 tempMaps = new ArrayList
>(); for (int i2 = 0; i2 < size; i2++) { //遍历list,调用get方法,获取list中的对象实例 Method getM = clazz.getDeclaredMethod("get", int.class); if (!getM.isAccessible()) { getM.setAccessible(true); s = getM.invoke(field.get(binFile), i2); map = ComUtil.getKeyAndValue(s); tempMaps.add(map); } } rsMap.put(field.getName(), tempMaps); } } else { //否则为普通类 field.setAccessible(true); Object value = field.get(binFile); map = ComUtil.getKeyAndValue(value); rsMap.put(field.getName(), map); } } } { //检查类数量 String[] cutStrs=new String[] {"bm0","bm1","bm2","bm3","bm4","bm5","bm6","bm7","bm8","bm9","bm10","bm11","bm12","bm13","bm14","bm15","bm16","bm17","bm18","bm19","bm20"}; for(i=0;i
) rsMap.get(cutStrs[i]))); // System.out.println(row.getString("Count")+":"+":"+ComUtil.getArrayListCapacity((ArrayList
) rsMap.get(cutStrs[i]))); } } } } return rsMap; } //根据规则解析map生成bin public static void saveMapBin(String rule, Map map, String path) { int i, s; JSONObject row; List
rs; List
list; Map m; String temStr = null; StringBuilder buf = new StringBuilder(); FileByte out = new FileByte(); String[] cutStrs = new String[] { "bm0", "bm1", "bm2", "bm3", "bm4", "bm5", "bm6", "bm7", "bm8", "bm9", "bm10", "bm11", "bm12", "bm13", "bm14", "bm15", "bm16", "bm17", "bm18", "bm19", "bm20" }; for (i = 0; i < cutStrs.length; i++) { row = getInfoByRootName(rule, cutStrs[i]); rs = getDefRuleInfosByRow(row); if (row.get("ifCycle").equals("true")) { list = (List) map.get(cutStrs[i]); for (Map lMap : list) { for (DefRule r : rs) { if (lMap.containsKey(r.getId())) { if (r.getType().equals("Byte")) { temStr = ComUtil.transByte(lMap.get(r.getId()).toString()); } else if (r.getType().equals("Integer")) { temStr = ComUtil.transInteger(lMap.get(r.getId()).toString()); } else if (r.getType().equals("Long")) { temStr = ComUtil.transLong(lMap.get(r.getId()).toString()); } else if (r.getType().equals("Single")) { temStr = ComUtil.transSingle(lMap.get(r.getId()).toString()); } else if (r.getType().equals("String")) { temStr = ComUtil.transString(lMap.get(r.getId()).toString()); } else if (r.getType().equals("?")) { temStr = lMap.get(r.getId()).toString(); } buf.append(temStr); } } } } else { m = (Map) map.get(cutStrs[i]); for (DefRule r : rs) { if (r.getType().equals("Byte")) { temStr = ComUtil.transByte(m.get(r.getId()).toString()); } else if (r.getType().equals("Integer")) { temStr = ComUtil.transInteger(m.get(r.getId()).toString()); } else if (r.getType().equals("Long")) { temStr = ComUtil.transLong(m.get(r.getId()).toString()); } else if (r.getType().equals("Single")) { temStr = ComUtil.transSingle(m.get(r.getId()).toString()); } else if (r.getType().equals("String")) { temStr = ComUtil.transString(m.get(r.getId()).toString()); } else if (r.getType().equals("?")) { temStr = m.get(r.getId()).toString(); } buf.append(temStr); } } } { for (s = 0; s < (int) (buf.length() / 2); s++) { try { out.writeByte(Integer.parseInt(buf.substring(s * 2, (s + 1) * 2), 16)); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } FileOutputStream fs; try { fs = new FileOutputStream(path); fs.write(out.getByte()); fs.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }}
BTLTooL
package code;import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Properties;import java.util.regex.Matcher;import java.util.regex.Pattern;import org.dom4j.Attribute;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.JSONObject;public class ComUtil {    //加载xml    // 此方法调用dom4j来解析xml       public static JSONObject XmlRead(String path) {           // 解析books.xml文件           // 创建SAXReader的对象reader           SAXReader reader = new SAXReader();           JSONObject jsonObject = new JSONObject();           try {               // 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。               Document document = reader.read(new File(path));               // 通过document对象获取根节点bookstore               Element bookStore = document.getRootElement();               // 通过element对象的elementIterator方法获取迭代器               Iterator it = bookStore.elementIterator();               // 遍历迭代器,获取根节点中的信息()               JSONArray jsonArray = new JSONArray();               while (it.hasNext()) {                   // System.out.println("=====开始遍历xml属性=====");                   Element book = (Element) it.next();                   Map
param = new HashMap
(); JSONArray nodeList = new JSONArray(); // 获取book的属性名以及 属性值 List
bookAttrs = book.attributes(); for (Attribute attr : bookAttrs) { //System.out.println("属性名:" + attr.getName() + "--属性值:" + attr.getValue()); param.put(attr.getName(), attr.getValue()); } jsonObject.put("attribute", jsonArray); // 解析子节点的信息 Iterator itt = book.elementIterator(); while (itt.hasNext()) { Element bookChild = (Element) itt.next(); List
bookAttrss = bookChild.attributes(); JSONObject obj = new JSONObject(); for (Attribute attr : bookAttrss) { //System.out.println("属性名:" + attr.getName() + "--属性值:" + attr.getValue()); obj.put(attr.getName(), attr.getValue()); } nodeList.add(obj); // System.out.println("节点名:" + bookChild.getName() + // "--节点值:" + bookChild.getStringValue()); } param.put("nodeList", nodeList); jsonArray.add(param); // System.out.println("=====结束遍历xml属性====="); } } catch (DocumentException e) { e.printStackTrace(); } return jsonObject; } //读取16进制文件 yjl public static byte[] readFile(String file) throws IOException{ InputStream is=new FileInputStream(file) ; int length=is.available() ; byte bt[]=new byte[length] ; is.read(bt) ; return bt; } //Integer.parseInt(buf.substring(bufTag, bufTag + cutL), 16)+""; public static String converLong(String param) { int len = param.length(); if(len!=8){ return "长度不符"; }else{ String str1 = param.substring(0,2); String str2 = param.substring(2,4); String str3 = param.substring(4,6); String str4 = param.substring(6,8); return String.valueOf(Integer.parseInt(str4+str3+str2+str1, 16)); } } public static String converInteger(String param) { int len = param.length(); if(len!=4){ return "长度不符"; }else{ String str1 = param.substring(0,2); String str2 = param.substring(2,4); String str3 =String.valueOf(Integer.parseInt(str2+str1, 16)); return str3; } } public static String converSingle(String param) { int len = param.length(); if(len!=8){ return "长度不符"; }else{
//3100cdcd String str1 = param.substring(0,2); String str2 = param.substring(2,4); String str3 = param.substring(4,6); String str4 = param.substring(6,8); return String.valueOf(Float.intBitsToFloat(Integer.valueOf(str4+str3+str2+str1, 16))); //Float f=0.15490197f; 反向 //System.out.println(Integer.toHexString(Float.floatToIntBits(f))); } } public static String converByte(String param) { int len = param.length(); if(len!=2){ return "长度不符"; }else{ String str1 = param.substring(0,2); return String.valueOf(Integer.parseInt(str1, 16)); } } public static String converString(String param) { int len = param.length(); if(len!=32){ return "长度不符"; }else{
//64 65 31 00 CD CD CD CD CD CD CD CD CD CD CD CD; int i=getCharacterPosition(param,"cd",1); if(i!=-1) { param=param.substring(0,i); System.out.println(param); param=convertHexToString(param); }else { param="解析错误"; } return param; } } public static String transLong(String param) { param=Integer.toHexString(Integer.parseInt(param))+""; int size=8; if(param.length()!=size){ param=formmatString(param,size,1,"0"); } String str1 = param.substring(0,2); String str2 = param.substring(2,4); String str3 = param.substring(4,6); String str4 = param.substring(6,8); return String.valueOf(str4+str3+str2+str1); } public static String transInteger(String param) { param=Integer.toHexString(Integer.parseInt(param))+""; int size=4; if(param.length()!=size){ param=formmatString(param,size,1,"0"); } String str1 = param.substring(0,2); String str2 = param.substring(2,4); return String.valueOf(str2+str1); } public static String transSingle(String param) { param=Integer.toHexString(Float.floatToIntBits(Float.parseFloat(param)))+""; int size=8; if(param.length()!=size){ param=formmatString(param,size,1,"0"); } String str1 = param.substring(0,2); String str2 = param.substring(2,4); String str3 = param.substring(4,6); String str4 = param.substring(6,8); return String.valueOf(str4+str3+str2+str1); //Float f=0.15490197f; 反向 //System.out.println(Integer.toHexString(Float.floatToIntBits(f))); } public static String transByte(String param) { param=Integer.toHexString(Integer.parseInt(param))+""; int size=2; if(param.length()!=size){ param=formmatString(param,size,1,"0"); } return String.valueOf(param); } public static String transString(String param) { param=convertStringToHex(param); int size=32; if(param.length()!=size){ //补位cd int i=(32-param.length())/2; for(int j=0;j
reMap = new HashMap
(); if (obj == null) return null; Field[] fields = obj.getClass().getDeclaredFields(); try { for(int i=0;i
List
removeNull(List
oldList) { // 你没有看错,真的是有 1 行代码就实现了 oldList.removeAll(Collections.singleton(null)); return (List
) oldList; } //获取单个对象的值 public static Map
getKeyAndValue(Object obj) { Map
map = new HashMap
(); // 得到类对象 Class userCla = (Class) obj.getClass(); /* 得到类中的所有属性集合 */ Field[] fs = userCla.getDeclaredFields(); for (int i = 0; i < fs.length; i++) { Field f = fs[i]; f.setAccessible(true); // 设置些属性是可以访问的 Object val = new Object(); try { val = f.get(obj); // 得到此属性的值 if(val!=null) { map.put(f.getName(), val);// 设置键值 } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } /* * String type = f.getType().toString();//得到此属性的类型 if * (type.endsWith("String")) { * System.out.println(f.getType()+"\t是String"); f.set(obj,"12") ; * //给属性设值 }else if(type.endsWith("int") || * type.endsWith("Integer")){ * System.out.println(f.getType()+"\t是int"); f.set(obj,12) ; //给属性设值 * }else{ System.out.println(f.getType()+"\t"); } */ } //System.out.println("单个对象的所有键值==反射==" + map.toString()); return map; } /* 处理字符串,进行前后补位 resultString ,表原字符串 length,处理后要求长度 flag,1表示前面增加,0表示后增加 str1,要补位的字符串 */ public static String formmatString(String resultString ,int length,int flag,String str1){ for(;resultString.getBytes().length
arrayList) { Class
arrayListClass = ArrayList.class; try { //获取 elementData 字段 Field field = arrayListClass.getDeclaredField("elementData"); //开始访问权限 field.setAccessible(true); //把示例传入get,获取实例字段elementData的值 Object[] objects = (Object[])field.get(arrayList); //返回当前ArrayList实例的容量值 return objects.length; } catch (Exception e) { e.printStackTrace(); return -1; } } }
ComUtil
rule_btl_wc4.xml

 

下图左边为生成的,右边为原生的,可以看到一模一样

 ---------------------------------7.9---------------------------------

由于安卓项目加载新包不顺利,所以去掉了对其他包的依赖重新写了一个方法解决

package com.zhfy.game.framework.tool;import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;import java.text.DecimalFormat;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;import com.badlogic.gdx.Gdx;import com.badlogic.gdx.files.FileHandle;import com.badlogic.gdx.utils.Array;import com.badlogic.gdx.utils.XmlReader;import com.badlogic.gdx.utils.XmlReader.Element;import com.zhfy.game.config.ResConfig;import com.zhfy.game.framework.ComUtil;import com.zhfy.game.framework.GameUtil;import com.zhfy.game.model.content.BTLDAO;import com.zhfy.game.model.content.DefRule;import com.zhfy.game.model.content.btl.BtlModule0;import com.zhfy.game.model.content.btl.BtlModule1;import com.zhfy.game.model.content.btl.BtlModule10;import com.zhfy.game.model.content.btl.BtlModule11;import com.zhfy.game.model.content.btl.BtlModule12;import com.zhfy.game.model.content.btl.BtlModule13;import com.zhfy.game.model.content.btl.BtlModule14;import com.zhfy.game.model.content.btl.BtlModule15;import com.zhfy.game.model.content.btl.BtlModule16;import com.zhfy.game.model.content.btl.BtlModule17;import com.zhfy.game.model.content.btl.BtlModule18;import com.zhfy.game.model.content.btl.BtlModule19;import com.zhfy.game.model.content.btl.BtlModule2;import com.zhfy.game.model.content.btl.BtlModule20;import com.zhfy.game.model.content.btl.BtlModule3;import com.zhfy.game.model.content.btl.BtlModule4;import com.zhfy.game.model.content.btl.BtlModule5;import com.zhfy.game.model.content.btl.BtlModule6;import com.zhfy.game.model.content.btl.BtlModule7;import com.zhfy.game.model.content.btl.BtlModule8;import com.zhfy.game.model.content.btl.BtlModule9;//此用来存放根据配置读取btl方法与根据配置保存btl方法public class BTLTooL {    //根据规则解析map生成bin    //rulePath为规则    //filePath输出路径 local    public static void saveBtl(BTLDAO btl,String rulePath,  String filePath) throws NumberFormatException, IOException {        Map ruleMap = getMapByRule(rulePath);        Map rsInfoMap = (Map) ruleMap.get("rsInfo");        Map rsDetailMap = (Map) ruleMap.get("rsDetail");        Map rsFunctionMap = (Map) ruleMap.get("rsFunction");        Map map=null;        try {            map = getBtlMap(btl);        } catch (Exception e1) {            e1.printStackTrace();        }        Map row;        int i, s;        List
rs; List
list; Map m = null; String temStr = null; //StringBuilder buf = new StringBuilder(); FileByte out = new FileByte(); String[] cutStrs = new String[] { "bm0", "bm1", "bm2", "bm3", "bm4", "bm5", "bm6", "bm7", "bm8", "bm9", "bm10", "bm11", "bm12", "bm13", "bm14", "bm15", "bm16", "bm17", "bm18", "bm19", "bm20" }; boolean tr = false; boolean ifCtEq0 = false; int c;int ruleSize=0,n=0;String tempBmId; {
//修正Count的循环次数 for(String str: cutStrs){
//如果是循环的,更新他对应的信息 if (rsInfoMap.containsKey(str)) { row = (Map) rsInfoMap.get(str); if (row.get("ifCycle").equals("true")) { ((Map) map.get("bm0")).put(row.get("Count"), ((List) map.get(str)).size()); //Gdx.app.log("btl修改对应size",row.get("Count")+":"+((List)map.get(cutStrs[i])).size()); } } } } for (i = 0; i < cutStrs.length; i++) { if (rsInfoMap.containsKey(cutStrs[i])) { row = (Map) rsInfoMap.get(cutStrs[i]); ruleSize=(int) ((Map) rsInfoMap.get(cutStrs[i])).get("Size"); if (row.get("ifCycle").equals("true") || row.get("ifCycle").equals("false")) { tr = row.get("ifCycle").equals( "true"); } else { if (row.get("ifCycle").toString().indexOf("==") != -1) { c = ComUtil.getCharacterPosition(row.get("ifCycle").toString(), "==", 1); if (c != -1) { try { tr = ((Map) map.get("bm0")).get(row.get("ifCycle").toString().substring(0, c)).equals(row.get("ifCycle").toString().substring(c + 2)); } catch (Exception e) { e.printStackTrace(); } if (!tr) { ifCtEq0 = true; } } } else if (row.get("ifCycle").toString().indexOf("!=") != -1) { c = ComUtil.getCharacterPosition(row.get("ifCycle").toString(), "!=", 1); if (c != -1) { try { tr = !((Map) map.get("bm0")).get(row.get("ifCycle").toString().substring(0, c)).equals(row.get("ifCycle").toString().substring(c + 2)); } catch (Exception e) { //e.printStackTrace(); } if (!tr) { ifCtEq0 = true; } } } } if (tr) { list = (List) map.get(cutStrs[i]); for (Map lMap : list) { for (n=1;n<=ruleSize;n++) { tempBmId=cutStrs[i]+"_"+n; if (lMap.containsKey(tempBmId)) { DefRule r=(DefRule) rsDetailMap.get(tempBmId); writeFile(out,r, lMap); //buf.append(temStr); } } } } else { if (!ifCtEq0 && map.get(cutStrs[i]) instanceof List) { m = (Map) ((List) map.get(cutStrs[i])).get(0); } else if (!ifCtEq0) { m = (Map) map.get(cutStrs[i]); for (n=1;n<=ruleSize;n++) { tempBmId=cutStrs[i]+"_"+n; DefRule r=(DefRule) rsDetailMap.get(tempBmId); writeFile(out,r, m); //buf.append(temStr); } } } } } FileHandle file = Gdx.files.local(filePath); file.writeBytes(out.getByte(), false); } //将rule处理为map //rsInfo {bm0={remark=主数据 128, id=bm0, Count=one, ifCycle=false}} //rsDetail {bm0_1={DefRule}} //使用gdx的方法根据rule读取数据,处理为到dao类 //rulePath规则路径 //rsbt为文件加载后的byte Gdx.files.internal("stage/" + str + ".btl").readBytes(); public static BTLDAO LoadBtl(String rulePath, byte[] rsbt) throws Exception { //将rule处理为map Map ruleMap = getMapByRule(rulePath); Map rsInfoMap = (Map) ruleMap.get("rsInfo"); Map rsDetailMap = (Map) ruleMap.get("rsDetail"); Map rsFunctionMap = (Map) ruleMap.get("rsFunction"); //byte[] rsbt = null; String cutStr = ""; int bufTag = 0; int cutSumCt = 1;//总循环次数 int mapW = 0, mapH = 0, i; Map rsMap = null; Map biMap = null; Map row; int line = 0; BTLDAO btl = new BTLDAO(); StringBuilder buf = new StringBuilder(); {
/*//读取bin try { //rsbt = ComUtil.readFile(filePath);//"D:\\test1.bin" rsbt = Gdx.files.internal(filePath).readBytes();//"D:\\test1.bin" } catch (Exception e) { e.printStackTrace(); }*/ // 十六进制标记 for (byte d : rsbt) { if (line % 1 == 0) { buf.append(String.format("%02x", d)); line++; } } } { //得到基础信息 cutStr = "bm0"; BtlModule0 bi = new BtlModule0(); rsMap = cutBtl(rsDetailMap, bi, buf, bufTag, cutSumCt,cutStr); bi = (BtlModule0) rsMap.get("T"); btl.setBm0(bi); bufTag = Integer.parseInt(rsMap.get("bufTag").toString()); biMap = ComUtil.JBeanToMap(bi); if (rsFunctionMap.containsKey("mapH")) { mapH = Integer.parseInt(biMap.get(rsFunctionMap.get("mapH")).toString()); } if (rsFunctionMap.containsKey("mapW")) { mapW = Integer.parseInt(biMap.get(rsFunctionMap.get("mapW")).toString()); } if (mapW * mapH == 0) { throw new Exception("没有得到有效的宽高"); } /**/ } { //重复读取所有基本信息 Object[] objects = new Object[] { (new BtlModule1()), (new BtlModule2()), (new BtlModule3()), (new BtlModule4()), (new BtlModule5()), (new BtlModule6()), (new BtlModule7()), (new BtlModule8()), (new BtlModule9()), (new BtlModule10()), (new BtlModule11()), (new BtlModule12()), (new BtlModule13()), (new BtlModule14()), (new BtlModule15()), (new BtlModule16()), (new BtlModule17()), (new BtlModule18()), (new BtlModule19()), (new BtlModule20()) }; String[] cutStrs = new String[] { "bm1", "bm2", "bm3", "bm4", "bm5", "bm6", "bm7", "bm8", "bm9", "bm10", "bm11", "bm12", "bm13", "bm14", "bm15", "bm16", "bm17", "bm18", "bm19", "bm20" }; boolean tr = false; boolean ifCtEq0 = false; int c; for (i = 0; i < objects.length; i++) { if (rsInfoMap.containsKey(cutStrs[i])) { row = (Map) rsInfoMap.get(cutStrs[i]); if (row.get("ifCycle").equals("true") || row.get("ifCycle").equals("false")) { tr = row.get("ifCycle") .equals( "true"); } else { if (row.get("ifCycle").toString().indexOf("==") != -1) { c = ComUtil.getCharacterPosition(row.get("ifCycle").toString(), "==", 1); if (c != -1) { try { tr = biMap.get(row.get("ifCycle").toString().substring(0, c)).equals(row.get("ifCycle").toString().substring(c + 2)); } catch (Exception e) { //e.printStackTrace(); } if (!tr) { ifCtEq0 = true; } } } else if (row.get("ifCycle").toString().indexOf("!=") != -1) { c = ComUtil.getCharacterPosition(row.get("ifCycle").toString(), "!=", 1); if (c != -1) { try { tr = !biMap.get(row.get("ifCycle").toString().substring(0, c)).equals(row.get("ifCycle").toString().substring(c + 2)); } catch (Exception e) { //e.printStackTrace(); } if (!tr) { ifCtEq0 = true; } } } } if (tr) { if (row.get("Count").equals("one")) { cutSumCt = 1; } else if ((row.get("Count").equals("sumGrid")||row.get("Count").equals("sumGride"))) { cutSumCt = mapW * mapH; } else { cutSumCt = Integer.parseInt((String) biMap.get(row.get("Count"))); } } else { if (ifCtEq0) { cutSumCt = 0; } else { cutSumCt = 1; } } rsMap = cutBtl(rsDetailMap, objects[i], buf, bufTag, cutSumCt,cutStrs[i]); ComUtil.setVal(btl, "set" + ComUtil.UpperInitial(cutStrs[i]), rsMap.get("T")); bufTag = Integer.parseInt(rsMap.get("bufTag").toString()); } } } {//是否有遗漏数据 String str= buf.substring(bufTag); if(!str.trim().equals("")) { throw new Exception("剩余未解析数据为:"+str); } } return btl; } //切割btl根据xml的记录 rsDetail, bi, buf, bufTag, cutSumCt //等待实际测试,如果结果不理想再去泛型 private static
Map
cutBtl(Map rs, T item, StringBuilder buf, int bufTag, int cycleCount,String bm) { Map
rsMap = new HashMap
(); List
ts = new ArrayList
(); Class clazz = item.getClass(); Field[] fieldName; Class clazs; Field f = null; int beginBufTag = bufTag; int cutL, c; String valueStr = null; String bmId = null;//拼接的id,由于安卓的反射顺序问题,所以采用这种方式 for (c = 0; c < cycleCount; c++) { fieldName = clazz.getDeclaredFields(); try { item = (T) clazz.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } clazs = item.getClass(); //for (n = 0; n < ruleSize; n++) { for (int i = 0; i < fieldName.length; i++) { bmId=bm+"_"+(i+1); if (rs.containsKey(bmId)) { // 创建实例 try { f = clazs.getDeclaredField(bmId); } catch (Exception e) { e.printStackTrace(); Gdx.app.log("创建实例",bmId); } f.setAccessible(true); DefRule r = (DefRule) rs.get(bmId); //System.out.println("B:Name1:"+r.getId()+" c:"+c+" bs:"+bufTag); valueStr = getCoverStr(r, buf, bufTag); /*if(c==0){ Gdx.app.log("CutBtl","B:item:"+item.toString()+" id:"+r.getId()+" c:"+c+" bs:"+bufTag+"~"+(bufTag + r.getSize())+" v:"+valueStr); }*/ bufTag = bufTag + r.getSize(); try { f.set(item, valueStr); } catch (Exception e) { e.printStackTrace(); } }/*else{ Gdx.app.log("CutBtl警告",bmId); }*/ } //} if (item != null) { ts.add(item); } } if (cycleCount == 1 && beginBufTag == 0) { rsMap.put("T", item); } else { ComUtil.removeNull(ts); rsMap.put("T", ts); } rsMap.put("bufTag", bufTag); return rsMap; } //将rule处理为map //rsInfo {bm0={remark=主数据 128, id=bm0, Count=one, ifCycle=false}} //rsDetail {bm0_1={DefRule}} public static Map getMapByRule(String rulePath) { XmlReader reader = ResConfig.reader; Element root = reader.parse(Gdx.files.internal(rulePath)); Map rsInfoMap = new HashMap();//存放ifCycle,Count,remark Map rsDetailMap = new HashMap();//存放每一条规则 Map rsFunctionMap = new HashMap();//存放function的id Map rsMap = new HashMap(); Array
authors = root.getChildrenByNameRecursively("Files"); int ruleSize = 0; //System.out.println("root.name:" + root.getName()); String[] mapStrs = new String[] { "bm0", "bm1", "bm2", "bm3", "bm4", "bm5", "bm6", "bm7", "bm8", "bm9", "bm10", "bm11", "bm12", "bm13", "bm14", "bm15", "bm16", "bm17", "bm18", "bm19", "bm20" }; for (int i = 0; i < mapStrs.length; i++) { Element bmElement = root.getChildByName(mapStrs[i]); if (bmElement != null) { Array
bmElements = bmElement.getChildrenByNameRecursively("bm"); ruleSize = 0; for (Element bm : bmElements) { ruleSize = ruleSize + 1; DefRule rule = new DefRule(); rule.setId(bm.get("id")); rule.setSize(bm.getInt("size")); rule.setName(bm.get("name")); rule.setRemark(bm.get("remark")); rule.setType(bm.get("type")); rule.setFunction(bm.get("function")); rule.setDefaul(bm.get("defaul")); rsDetailMap.put(rule.getId(), rule); if (!rule.getFunction().equals("no") && !rule.getFunction().equals("")) { rsFunctionMap.put(rule.getFunction(), rule.getId()); //System.out.println(rule.getFunction()+":"+rule.getId()); } } Map tempMap = new HashMap(); tempMap.put("id", mapStrs[i]); tempMap.put("ifCycle", bmElement.get("ifCycle")); tempMap.put("Count", bmElement.get("Count")); tempMap.put("remark", bmElement.get("remark")); tempMap.put("Size", ruleSize);//存放该子条目的条数 rsInfoMap.put(mapStrs[i], tempMap); } } rsMap.put("rsInfo", rsInfoMap); rsMap.put("rsDetail", rsDetailMap); rsMap.put("rsFunction", rsFunctionMap); return rsMap; } public static String getCoverStr(DefRule r, StringBuilder buf, int bufTag) { int cutL = r.getSize(); int str = 0; if (cutL != 0) { str = Integer.parseInt(buf.substring(bufTag, bufTag + cutL), 16); } return str + ""; } public static void writeFile(FileByte out,DefRule r, Map m) throws NumberFormatException, IOException { String temStr; int cutL = r.getSize(); if (m.containsKey(r.getId())) { if (r.getSize()==2) { out.writeByte(Integer.parseInt(m.get(r.getId()).toString())); }else if(r.getSize()==4) { out.writeShort(Integer.parseInt(m.get(r.getId()).toString())); }else if(r.getSize()==8) { out.writeInt(Integer.parseInt(m.get(r.getId()).toString())); } } else { if (r.getSize()==2) { out.writeByte( Integer.parseInt( r.getDefaul())); }else if(r.getSize()==4) { out.writeShort( Integer.parseInt( r.getDefaul())); }else if(r.getSize()==8) { out.writeInt( Integer.parseInt( r.getDefaul())); } } } //读取btl,转为map public static Map getBtlMap(BTLDAO binFile) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { int i; Object om; Map map = null; List
> tempMaps; Map
rsMap = new HashMap(); Object s; { //遍历btl Field[] fields = binFile.getClass().getDeclaredFields();//Object是已经被赋值的对象实例 for (Field field : fields) { if (!field.isAccessible()) { field.setAccessible(true); } //如果是list类 if (List.class.isAssignableFrom(field.getType())) { Type t = field.getGenericType(); if (t instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) t; Class clz = (Class) pt.getActualTypeArguments()[0];//得到对象list中实例的类型 if (field.get(binFile) != null) { Class clazz = field.get(binFile).getClass();//获取到属性的值的Class对象 Method m = clazz.getDeclaredMethod("size"); int size = (Integer) m.invoke(field.get(binFile));//调用list的size方法,得到list的长度 tempMaps = new ArrayList
>(); for (int i2 = 0; i2 < size; i2++) { //遍历list,调用get方法,获取list中的对象实例 Method getM = clazz.getDeclaredMethod("get", int.class); if (!getM.isAccessible()) { getM.setAccessible(true); s = getM.invoke(field.get(binFile), i2); map = ComUtil.getKeyAndValue(s); tempMaps.add(map); } } rsMap.put(field.getName(), tempMaps); } } } else { //否则为普通类 field.setAccessible(true); Object value = field.get(binFile); map = ComUtil.getKeyAndValue(value); rsMap.put(field.getName(), map); } } } return rsMap; }}
BTLTooL
package com.zhfy.game.framework;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.UnsupportedEncodingException;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Properties;import java.util.Random;import java.util.Set;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.swing.JFileChooser;import javax.swing.filechooser.FileNameExtensionFilter;import javax.swing.filechooser.FileSystemView;import com.badlogic.gdx.utils.XmlReader;public class ComUtil {    //本工具类主要涉及通常使用的工具类            //加载xml    // 此方法调用dom4j来解析xml    /*public static JSONObject XmlRead(String path) {        // 解析books.xml文件        // 创建SAXReader的对象reader        SAXReader reader = new SAXReader();        JSONObject jsonObject = new JSONObject();        try {            // 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。            Document document = reader.read(new File(path));            // 通过document对象获取根节点bookstore            Element bookStore = document.getRootElement();            // 通过element对象的elementIterator方法获取迭代器            Iterator it = bookStore.elementIterator();            // 遍历迭代器,获取根节点中的信息()            JSONArray jsonArray = new JSONArray();                        while (it.hasNext()) {                                // System.out.println("=====开始遍历xml属性=====");                Element book = (Element) it.next();                Map
param = new HashMap
(); JSONArray nodeList = new JSONArray(); // 获取book的属性名以及 属性值 List
bookAttrs = book.attributes(); for (Attribute attr : bookAttrs) { //System.out.println("属性名:" + attr.getName() + "--属性值:" + attr.getValue()); param.put(attr.getName(), attr.getValue()); } jsonObject.put("attribute", jsonArray); // 解析子节点的信息 Iterator itt = book.elementIterator(); while (itt.hasNext()) { Element bookChild = (Element) itt.next(); List
bookAttrss = bookChild.attributes(); JSONObject obj = new JSONObject(); for (Attribute attr : bookAttrss) { //System.out.println("属性名:" + attr.getName() + "--属性值:" + attr.getValue()); obj.put(attr.getName(), attr.getValue()); } nodeList.add(obj); // System.out.println("节点名:" + bookChild.getName() + // "--节点值:" + bookChild.getStringValue()); } param.put("nodeList", nodeList); jsonArray.add(param); // System.out.println("=====结束遍历xml属性====="); } } catch (DocumentException e) { e.printStackTrace(); } return jsonObject; } public static JSONObject XmlReadByLibgdx(String path) { // 解析books.xml文件 // 创建SAXReader的对象reader SAXReader reader = new SAXReader(); JSONObject jsonObject = new JSONObject(); try { // 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。 Document document = reader.read(new ByteArrayInputStream(path.getBytes("UTF-8"))); // 通过document对象获取根节点bookstore Element bookStore = document.getRootElement(); // 通过element对象的elementIterator方法获取迭代器 Iterator it = bookStore.elementIterator(); // 遍历迭代器,获取根节点中的信息() JSONArray jsonArray = new JSONArray(); while (it.hasNext()) { // System.out.println("=====开始遍历xml属性====="); Element book = (Element) it.next(); Map
param = new HashMap
(); JSONArray nodeList = new JSONArray(); // 获取book的属性名以及 属性值 List
bookAttrs = book.attributes(); for (Attribute attr : bookAttrs) { //System.out.println("属性名:" + attr.getName() + "--属性值:" + attr.getValue()); param.put(attr.getName(), attr.getValue()); } jsonObject.put("attribute", jsonArray); // 解析子节点的信息 Iterator itt = book.elementIterator(); while (itt.hasNext()) { Element bookChild = (Element) itt.next(); List
bookAttrss = bookChild.attributes(); JSONObject obj = new JSONObject(); for (Attribute attr : bookAttrss) { //System.out.println("属性名:" + attr.getName() + "--属性值:" + attr.getValue()); obj.put(attr.getName(), attr.getValue()); } nodeList.add(obj); // System.out.println("节点名:" + bookChild.getName() + // "--节点值:" + bookChild.getStringValue()); } param.put("nodeList", nodeList); jsonArray.add(param); // System.out.println("=====结束遍历xml属性====="); } } catch (Exception e) { e.printStackTrace(); } return jsonObject; }*/ //读取16进制文件 public static byte[] readFile(String file) throws IOException { InputStream is = new FileInputStream(file); int length = is.available(); byte bt[] = new byte[length]; is.read(bt); return bt; } public static String converInteger(String param) { int len = param.length(); if (len != 8) { return "长度不符"; } else { return String.valueOf(Integer.parseInt(param, 16)); } } public static String converShort(String param) { int len = param.length(); if (len != 4) { return "长度不符"; } else { return String.valueOf(Integer.parseInt(param, 16)); } } public static String converSingle(String param) { int len = param.length(); if (len != 8) { return "长度不符"; } else { //3100cdcd return String.valueOf(Float.intBitsToFloat(Integer.valueOf(param, 16))); //Float f=0.15490197f; 反向 //System.out.println(Integer.toHexString(Float.floatToIntBits(f))); } } public static String converByte(String param) { int len = param.length(); if (len != 2) { return "长度不符"; } else { return String.valueOf(Integer.parseInt(param.substring(0, 2), 16)); } } public static String converString(String param) { int len = param.length(); if (len != 32) { return "长度不符"; } else { //64 65 31 00 CD CD CD CD CD CD CD CD CD CD CD CD; int i = getCharacterPosition(param, "cd", 1); if (i != -1) { param = param.substring(0, i); //System.out.println(param); param = convertHexToString(param); } else { param = "解析错误"; } return param; } } public static String transInteger(String param) { param = Integer.toHexString(Integer.parseInt(param)) + ""; int size = 8; if (param.length() != size) { param = formmatString(param, size, 1, "0"); } String str1 = param.substring(0, 2); String str2 = param.substring(2, 4); String str3 = param.substring(4, 6); String str4 = param.substring(6, 8); return String.valueOf(param); } public static String transShort(String param) { param = Integer.toHexString(Integer.parseInt(param)) + ""; int size = 4; if (param.length() != size) { param = formmatString(param, size, 1, "0"); } String str1 = param.substring(0, 2); String str2 = param.substring(2, 4); return String.valueOf(param); } public static String transSingle(String param) { param = Integer.toHexString(Float.floatToIntBits(Float.parseFloat(param))) + ""; int size = 8; if (param.length() != size) { param = formmatString(param, size, 1, "0"); } String str1 = param.substring(0, 2); String str2 = param.substring(2, 4); String str3 = param.substring(4, 6); String str4 = param.substring(6, 8); return String.valueOf(param); //Float f=0.15490197f; 反向 //System.out.println(Integer.toHexString(Float.floatToIntBits(f))); } public static String transByte(String param) { param = Integer.toHexString(Integer.parseInt(param)) + ""; int size = 2; if (param.length() != size) { param = formmatString(param, size, 1, "0"); } return String.valueOf(param); } public static String transString(String param) { param = convertStringToHex(param); int size = 32; if (param.length() != size) { //补位cd int i = (32 - param.length()) / 2; for (int j = 0; j < i; j++) { param = param + "cd"; } } return param; } public static String convertStringToHex(String str) { char[] chars = str.toCharArray(); StringBuffer hex = new StringBuffer(); for (int i = 0; i < chars.length; i++) { hex.append(Integer.toHexString((int) chars[i])); } return hex.toString(); } public static String convertHexToString(String hex) { StringBuilder sb = new StringBuilder(); StringBuilder temp = new StringBuilder(); //49204c6f7665204a617661 split into two characters 49, 20, 4c... for (int i = 0; i < hex.length() - 1; i += 2) { //grab the hex in pairs String output = hex.substring(i, (i + 2)); //convert hex to decimal int decimal = Integer.parseInt(output, 16); //convert the decimal to character sb.append((char) decimal); temp.append(decimal); } return sb.toString(); } public static int getCharacterPosition(String url, String s, int i) { //这里是获取"/"符号的位置 lastindexof从字符串末尾开始检索,检索到子字符 Matcher slashMatcher = Pattern.compile(s).matcher(url); int mIdx = 0; while (slashMatcher.find()) { mIdx++; //当"/"符号第i次出现的位置 if (mIdx == i) { break; } } int rs; try { rs = slashMatcher.start(); } catch (Exception e) { rs = -1; } return rs; } //对象转Map public static Map JBeanToMap(Object obj) { Map
reMap = new HashMap
(); if (obj == null) return null; Field[] fields = obj.getClass().getDeclaredFields(); try { for (int i = 0; i < fields.length; i++) { try { Field f = obj.getClass().getDeclaredField(fields[i].getName()); f.setAccessible(true); Object o = f.get(obj); reMap.put(fields[i].getName(), o); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } catch (SecurityException e) { e.printStackTrace(); } return reMap; } //示例 setVal(obj,"setUpdateUser","修改人"); 给对象赋值 public static void setVal(Object obj, String methodName, Object value) { if (value == null || obj == null) { return; } //MethodAccess access = MethodAccess.get(obj.getClass()); //access.invoke(obj, methodName, value); String method_name = methodName; Method[] methods = obj.getClass().getMethods(); for (Method method : methods) { /** * 因为这里只是调用bean中属性的set方法,属性名称不能重复 所以set方法也不会重复,所以就直接用方法名称去锁定一个方法 * (注:在java中,锁定一个方法的条件是方法名及参数) **/ if (method.getName().equals(method_name)) { Class[] parameterC = method.getParameterTypes(); try { /** * 如果是基本数据类型时(如int、float、double、byte、char、boolean) * 需要先将Object转换成相应的封装类之后再转换成对应的基本数据类型 否则会报 * ClassCastException **/ if (parameterC[0] == int.class) { method.invoke(obj, ((Integer) value).intValue()); break; } else if (parameterC[0] == float.class) { method.invoke(obj, ((Float) value).floatValue()); break; } else if (parameterC[0] == double.class) { method.invoke(obj, ((Double) value).doubleValue()); break; } else if (parameterC[0] == byte.class) { method.invoke(obj, ((Byte) value).byteValue()); break; } else if (parameterC[0] == char.class) { method.invoke(obj, ((Character) value).charValue()); break; } else if (parameterC[0] == boolean.class) { method.invoke(obj, ((Boolean) value).booleanValue()); break; } else { method.invoke(obj, parameterC[0].cast(value)); break; } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } } } } //map转对象 public static Object mapToJBean(Class
clazz, Map
map) throws Exception { Object javabean = clazz.newInstance(); // 构建对象 Method[] methods = clazz.getMethods(); // 获取所有方法 //MethodAccess access = MethodAccess.get(clazz); for (Method method : methods) { if (method.getName().startsWith("set")) { String field = method.getName(); // 截取属性名 field = field.substring(field.indexOf("set") + 3); field = field.toLowerCase().charAt(0) + field.substring(1); if (map.containsKey(field)) { method.invoke(javabean, map.get(field)); //access.invoke(javabean, method.getName(), map.get(field)); } } } return javabean; } //将第一个字母大写 public static String UpperInitial(String str) { if (str != null && str != "") { str = str.substring(0, 1).toUpperCase() + str.substring(1); } return str; } //List 集合去除null元素 public static
List
removeNull(List
oldList) { // 你没有看错,真的是有 1 行代码就实现了 oldList.removeAll(Collections.singleton(null)); return (List
) oldList; } //获取单个对象的值 public static Map
getKeyAndValue(Object obj) { Map
map = new HashMap
(); // 得到类对象 Class userCla = (Class) obj.getClass(); /* 得到类中的所有属性集合 */ Field[] fs = userCla.getDeclaredFields(); for (int i = 0; i < fs.length; i++) { Field f = fs[i]; f.setAccessible(true); // 设置些属性是可以访问的 Object val = new Object(); try { val = f.get(obj); // 得到此属性的值 if (val != null) { map.put(f.getName(), val);// 设置键值 } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } //System.out.println("单个对象的所有键值==反射==" + map.toString()); return map; } /* * 处理字符串,进行前后补位 resultString ,表原字符串 length,处理后要求长度 flag,1表示前面增加,0表示后增加 * str1,要补位的字符串 */ public static String formmatString(String resultString, int length, int flag, String str1) { for (; resultString.getBytes().length < length;) { if (flag == 1) { resultString = str1 + resultString; } else { resultString = resultString + str1; } } return resultString; } //使用反射获取list大小 public static int getArrayListCapacity(ArrayList
arrayList) { Class
arrayListClass = ArrayList.class; try { //获取 elementData 字段 Field field = arrayListClass.getDeclaredField("elementData"); //开始访问权限 field.setAccessible(true); //把示例传入get,获取实例字段elementData的值 Object[] objects = (Object[]) field.get(arrayList); //返回当前ArrayList实例的容量值 return objects.length; } catch (Exception e) { e.printStackTrace(); return -1; } } public static boolean isEmpty(CharSequence cs) { return (cs == null) || (cs.length() == 0); } //清空右边 public static String rightTrim(String str) { if (str == null) { return ""; } int length = str.length(); for (int i = length - 1; i >= 0; i--) { if (str.charAt(i) != 0x20) { break; } length--; } return str.substring(0, length); } //将首字母大写 public static String captureName(String name) { char[] cs = name.toCharArray(); cs[0] -= 32; return String.valueOf(cs); } //获得list出现最多的数据 public static String getListMostRepeatData(List
l) { String regex; Pattern p; Matcher m; String tmp = ""; String tot_str = l.toString(); int max_cnt = 0; String max_str = ""; for(Object str : l) { if (tmp.equals(str)) continue; tmp = str.toString(); regex = str.toString(); p = Pattern.compile(regex); m = p.matcher(tot_str); int cnt = 0; while(m.find()) { cnt++; } //System.out.println(str + ":" + cnt); if (cnt > max_cnt) { max_cnt = cnt; max_str = str.toString(); } } //System.out.println(" 出现的最大次数的字符串是 " + max_str) ; return max_str; } //list值交换位置 public static void swap(List
list, int i, int j) { final List l = list; l.set(i, l.set(j, l.get(i))); } //遍历获取map的key值 public static List
getKeyByMap(Map map) { List
rs = new ArrayList
(); for (Object key : map.keySet()) { rs.add(Integer.parseInt(key.toString())); } return rs; } //计算概率 100为100%出现 //例如20 s:1000 y:220 n:780 public static boolean ifGet(int chance) { return (chance> ((int) (Math.random() * (100 - 0) + 0))); } //获得两个整数范围之间的随机数 public static int getRandom(int x, int y) { Random random = new Random(); int num = -1; //说明:两个数在合法范围内,并不限制输入的数哪个更大一些 if(x<0||y<0) { return num; }else { int max = x>y?x:y; int min = x
List
deepCopy(List
src) throws IOException, ClassNotFoundException { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(byteOut); out.writeObject(src); ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray()); ObjectInputStream in = new ObjectInputStream(byteIn); @SuppressWarnings("unchecked") List
dest = (List
) in.readObject(); return dest; } /** * 利用正则表达式判断字符串是否是数字 * @param str * @return */ public static boolean isNumeric(String str){ if(str==null){ return false; } Pattern pattern = Pattern.compile("[0-9]*"); Matcher isNum = pattern.matcher(str); if( !isNum.matches() ){ return false; } return true; } public static byte[] File2byte(String filePath) { byte[] buffer = null; try { File file = new File(filePath); FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int n; while ((n = fis.read(b)) != -1) { bos.write(b, 0, n); } fis.close(); bos.close(); buffer = bos.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buffer; } public static void byte2File(byte[] buf, String filePath, String fileName) { BufferedOutputStream bos = null; FileOutputStream fos = null; File file = null; try { File dir = new File(filePath); if (!dir.exists() && dir.isDirectory()) { dir.mkdirs(); } file = new File(filePath + File.separator + fileName); fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(buf); } catch (Exception e) { e.printStackTrace(); } finally { if (bos != null) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } //从一堆list中获取一列 public static
List
listToList(Collection
list,String fieldName) throws Exception { List
ret = new ArrayList(); List
getStrs=null; List
getMethods=new ArrayList
(); for(T t:list){ if(getStrs==null){ getStrs = new ArrayList
(); for(String s:fieldName.split("\\.")){ getStrs.add("get"+s.substring(0,1).toUpperCase()+s.substring(1)); } } Object value = t; for(int i=0;i
去重 public static List
getNewList(List
list){ if(null == list || list.size()<2) return list; Set
set = new HashSet
(); List
newList = new ArrayList
(); for (Integer i:list) { if(set.add(i)){ newList.add(i); } } return newList; } //判断a是否完全包含b public static boolean ifListContainList(List
a,List b){ boolean rs=true; for(Object i:b){ if(!a.contains(i)){ rs=false; } } return rs; } public static boolean ifListContainListByInteger(List
a,List
b){ boolean rs=true; for(int i:b){ if(!a.contains(i)){ rs=false; } } return rs; } //随机从list中取一个 regionGrid.get(ComUtil.getOneByListRand(regionGrid)) public static int getOneByListRand(List list){ return getRandom(0,list.size()); }}
ComUtil

转载于:https://www.cnblogs.com/tysk/p/10916043.html

你可能感兴趣的文章
mysql基础语句
查看>>
cassandra vs mongo (1)存储引擎
查看>>
Visual Studio基于CMake配置opencv1.0.0、opencv2.2
查看>>
MySQL索引背后的数据结构及算法原理
查看>>
#Leetcode# 209. Minimum Size Subarray Sum
查看>>
SDN第四次作业
查看>>
django迁移数据库错误
查看>>
yii 跳转页面
查看>>
洛谷 1449——后缀表达式(线性数据结构)
查看>>
Data truncation: Out of range value for column 'Quality' at row 1
查看>>
Dirichlet分布深入理解
查看>>
字符串处理
查看>>
HtmlUnitDriver 网页内容动态抓取
查看>>
ad logon hour
查看>>
获得进程可执行文件的路径: GetModuleFileNameEx, GetProcessImageFileName, QueryFullProcessImageName...
查看>>
证件照(1寸2寸)拍摄处理知识汇总
查看>>
罗马数字与阿拉伯数字转换
查看>>
Eclipse 反编译之 JadClipse
查看>>
Python入门-函数
查看>>
距离公式汇总以及Python实现
查看>>