package utils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class DataUtilsSingle { public JSONObject innerJSON; public JSONObject outerJSON; //读取path路径的txt文件 public void txt2String(String path) { //StringBuilder为拼接字符串,减少对象的创建 StringBuilder track_info_outer = new StringBuilder(); StringBuilder track_info_inner = new StringBuilder(); //文件读取必须得用try catch,文件按行读取 try { File file = new File(path); BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件 String s; boolean isInner = false; while ((s = br.readLine()) != null) {//使用readLine方法,一次读一行 String result = s.trim();//去空白,末尾或者开头。去空格 //内外层数据分离,用{表示track_info内层数据开始,用},表示track_info内层数据结束。有的埋点数据内层有"utparam":"{ // * \"yk_abtest\":\"592:1381\" // * }",这种数据,不能以}作为内层结束判断的标识 /** * track_info={ * "k":"名侦探柯南", * "object_num":3, * "aaid":"074d90da3c8602ec629104ee7a57e796", * "utparam":"{ * \"yk_abtest\":\"592:1381\" * }", * "newArch":"1", * "object_title":"30-60分钟", * "source_from":"home" * }, * spm=a2h0c.8166622.PhoneSokuFilter.sfilter_3, * scm=20140669.search.filter.filter_30-60分钟, * pid=64b6847e992c4c45 */ if (result.contains("{")) { isInner = true; } else if (result.contains("},")) { isInner = false; //"A=1,B=2,C=3..." track_info_inner.append(result); } boolean con = result.contains("},"); if (!con) { if (isInner) { track_info_inner.append(result); } else { track_info_outer.append(result); } } } br.close(); //track_info_inner中等号(=)第一次出现的位置 int firstIndex = track_info_inner.indexOf("="); //截取inner字符串,json格式{}里所有内容,从{开始截取,直到}的位置,最后一位为"," String innerStr = track_info_inner.substring(firstIndex + 1); if (innerStr.endsWith(",")) { innerStr = innerStr.substring(0, innerStr.length() - 1); } String[] outer = track_info_outer.toString().split(","); innerJSON = JSON.parseObject(innerStr); outerJSON = new JSONObject(); for (int i = 0; i < outer.length; i++) { String[] array = outer[i].split("="); outerJSON.put(array[0].trim(), array[1].trim()); } } catch (Exception e) { e.printStackTrace(); } } }
待续。。。