java基础数据类型和处理
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSON; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; import java.math.BigDecimal; import java.text.DecimalFormat; import java.util.Collections; import java.util.Comparator; import java.lang.reflect.Array; import java.util.*; import java.util.Map; import java.text.MessageFormat; import java.util.Random; public class JavaBasic { //class_variable,for class object.VarName static String name = "ss"; // instance variable,just for instance callable private String addr = "south surface"; //without return result ,static method can be callable by static method and class, // but can't be call by method or instance public static void printMethod() { System.out.println("iammmm"); } void defineArrays() { int[] ai = {1, 2, 3, 4}; Arrays.fill(ai, 5); for (int i = 0; i < ai.length; i++) { System.out.println(false); } } /** * format str : python "{0},{1}".foramt(v1,v2) * python str: "%s is ,%s is ".format(v1,v2) */ public String formatStr(String str) { String newstr = "my name is {0},age is {1}"; return (MessageFormat.format(newstr, "1", "22")); } /** * non static can't callable by static method ,just for normal method */ String defineStringMethod() { String str = formatStr("sss"); System.out.println(str); return "ss"; } /** * create map */ private Map<String, Object> createDict() { Map<String, Object> map = new HashMap<String, Object>(); map.put("key", 1); map.put("key2", "v2"); System.out.println(map); return map; } String defineChar() { char[] mychar = {'a', 'b'}; return new String(mychar); } // /** * define array of int, * and print Array.toString(arrayObject) */ void getArrayToStr() { String[][] str = new String[3][4]; str[0][0] = new String("Good"); Object O = str[0][0]; int[] my = new int[]{1, 2, 3}; //数组对象转字符串输出 System.out.println(Arrays.toString(my) + " " + O); } /** * get type of Object * * @return : type String */ public void type(Object object) { String tp = String.valueOf(object.getClass().getName()); System.out.println(tp.split("\\.").getClass().getName()); String[] array = tp.split("\\."); //数组转列表 List<String> list = Arrays.asList(array); String lastStr = list.get(array.length - 1); System.out.println(lastStr); // return lastStr; } /** * ArrayList to Array : list1.toArray(array) */ public void createArrayList() { List<String> list1 = new ArrayList<String>(); list1.add("index1"); list1.add("index2"); String[] test = list1.getClass().getName().split("\\."); // array to arrayList List<String> o = Arrays.asList(test); String[] array = new String[list1.size()]; // ArrayList to ARRAY String[] aa = list1.toArray(array); System.out.println("list1 type is :" + list1.getClass().getName()); System.out.println(Arrays.toString(aa)); } String[] getArray() { String[] m = new String[1]; return m; } /** * enumerate element and index : * * @return : ArrayList: [[index,value],[index1,value1]] */ void enumerateList() { List<String> list1 = new ArrayList<String>(); list1.add("index1"); list1.add("index2"); List<Object> all = new ArrayList<Object>(); for (int i = 0; i < list1.size(); i++) { List<Object> vec = new ArrayList<Object>(); vec.add(i); vec.add(list1.get(i)); all.add(vec); } System.out.println(all); } /** * iter map by foreach ,but it cant change key or value in the iteral : */ List<Object> iterMap() { List<Object> out = new ArrayList<Object>(); Map<String, Object> map = createDict(); for (String k : map.keySet()) { List<Object> in = new ArrayList<Object>(); String value = String.valueOf(map.get(k)); in.add(k); in.add(value); out.add(in); } System.out.println(out); return out; } /** * iter Map by use entrySet() : python dict.items(): */ void iterMap2() { List<Object> out = new ArrayList<Object>(); Map<String, Object> map = createDict(); for (Map.Entry<String, Object> item : map.entrySet()) { List<Object> in = new ArrayList<Object>(); String k = String.valueOf(item.getKey()); String v = String.valueOf(item.getValue()); in.add(0, k); in.add(1, v); out.add(in); } System.out.println(out); } /** * list remove element : */ void removeList() { // == 比对象,equals 比value List<Integer> out = new ArrayList<Integer>(); out.add(1); out.add(3); out.add(1); for (int i = 0; i < out.size(); i++) { if (out.get(i).equals(1)) { out.remove(i); } } System.out.println(out); } /** * SIMPLE java return :三目运算: */ int javaSimple() { int a, b, c; a = 10; b = 1; // c= ; return (a == 1) ? a : b; } /** * calculator timeInterval init type is long :100L: * * @return : String */ String timercount() throws InterruptedException { long date = new Date().getTime(); Thread.sleep(1000); long date_end = new Date().getTime(); String millions = String.valueOf(date_end - date); return millions; } /** * sort ArrayList for same type elements in list */ public static void sortbyCollect() { List<Integer> aa = new ArrayList<>(); List<Integer> bb = new ArrayList<>(); bb.add(100); aa.add(9); aa.add(4); aa.set(0, 99); aa.addAll(bb); Collections.sort(aa); Collections.reverse(aa); System.out.println(aa.toString()); } public Map<String, String> sortMap(Map map) { System.out.println(map); List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, String>>() { public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) { return o1.getValue().compareTo(o2.getValue()); } }); System.out.println(map); return map; } void listWhileHas() { ArrayList<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); //用迭代器 遍历 ListIterator<String> it = list.listIterator(); while (it.hasNext()) { //添加泛型之后 可以省去 强转了行的麻烦 String next = it.next(); System.out.println(next); } } /** * gen timestamp str for example: * 15576676767676 */ public static String timestamp() { return String.valueOf(System.currentTimeMillis()); } /** * random ArrayList of [min,max) or [min,max] */ public static List genRandomlist(int START, int END) { // 可以取到边界值上下 List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < END - START + 1; i++) { int numeric = new Random().nextInt(END - START + 1) + START; list.add(numeric); } System.out.println(list); return list; } /** * random ArrayList of [min,max) or [min,max] */ public static List mathRandom(int min, int max) { // max-min 不加1,只可以到[0,10);max-min+1 [1,10] List list = new ArrayList(); for (int i = 0; i < max - min; i++) { int num = (int) (Math.random() * (max - min + 1) + min); list.add(num); } System.out.println(list); return list; } /** * gen (0,1) str */ public static String genfloatZeroandOne() { double db = new Random().nextDouble() * 1 + 0; // DecimalFormat df = new DecimalFormat("0.00"); // return df.format(floats); float ft = (float) db; System.out.println(db);//四舍弃,五入 return String.format("%.3f", db); } /** * TYPE Transfer */ public static void chageType(String str) { float ft = Float.valueOf(str).floatValue(); byte b = Byte.parseByte(str); short t = Short.parseShort(str); int i = Integer.parseInt(str); long l = Long.parseLong(str); Float f = Float.parseFloat(str); Double d = Double.parseDouble(str); System.out.println(ft); } public static void genSecureRandom(int start, int end) { } /** * gen uuidString */ public static void genuuid() { String uuidstr = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase(); System.out.println(uuidstr); } /** * time format,default Calender.get() is int * month start by 0 */ public static String timeFormat() { /** Calendar now = Calendar.getInstance(); String year=String.valueOf(now.get(Calendar.YEAR)); String month=String.valueOf(now.get(Calendar.MONTH) + 1); String day=String.valueOf(now.get(Calendar.DAY_OF_MONTH)); String hour=String.valueOf(now.get(Calendar.HOUR_OF_DAY)); String min=String.valueOf(now.get(Calendar.MINUTE)); String seconds=String.valueOf(now.get(Calendar.SECOND)); String str="%s-%s-%s %s:%s:%s"; String curtime= String.format(str,year,month,day,hour,min,seconds); */ Date d = new Date(); SimpleDateFormat simpeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String curtimestamp = simpeformat.format(d); System.out.println(curtimestamp); return curtimestamp; } /** * readfile method * @return :fileString * by FileInputStream */ public static String readfile(String filepath) throws IOException { StringBuffer sb = new StringBuffer(); File file = new File(filepath); if (file.exists() && file.isFile()) { FileInputStream fip = new FileInputStream(file); InputStreamReader reader = new InputStreamReader(fip, "UTF-8"); while (reader.ready()) { /** append char to string buffer*/ sb.append((char) reader.read()); } /** close reader and fip stream */ reader.close(); fip.close(); } System.out.println(sb.toString()); return sb.toString(); } /** * writefile method *@return :null * @param : by FileOutputStream */ public static void writefile(String pdir,String filename) throws IOException { File dir =new File(pdir); if(!dir.exists()){ /** mkdir pdir */ dir.mkdir(); } File filepath=new File(pdir+filename); if(!filepath.exists()){ /** touch file */ filepath.createNewFile(); FileOutputStream fop = new FileOutputStream(filepath); OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8"); writer.write("9999dftest花"); /**close write and fop stream */ writer.close(); fop.close(); }else{ System.out.println("file already exist"); FileOutputStream fop = new FileOutputStream(filepath); OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8"); writer.append("我爱singer"); writer.append("\n9999dftest花"); /**close write and fop stream */ writer.close(); fop.close(); } } /** delete file*/ public static void delfile(String filepath){ File file =new File(filepath); if(file.exists()&&file.isFile()){ file.delete(); System.out.println("file delete ok "); }else{ System.out.println("file not exist"); } } /** * delete dir * @return:null * @warning: clear all dirs and files under path and strart del path */ public static void deleteDir(String path) { /** list pathdir under it's file and dir*/ File dir = new File(path); if (dir.exists()) { File[] tmp = dir.listFiles(); for (int i = 0; i < tmp.length; i++) { if (tmp[i].isDirectory()) { deleteDir(path + "/" + tmp[i].getName()); } else { tmp[i].delete(); } } /** clear all dirs and files under path and strart del path */ dir.delete(); } } public static String bufferReadeFile(String filepath){ StringBuffer sb=new StringBuffer(); try{ FileReader reader=new FileReader(filepath); BufferedReader br =new BufferedReader(reader); String line; while((line=br.readLine())!=null){ sb.append(line); } }catch (IOException e){ e.printStackTrace(); } /**test output*/ System.out.println(sb.toString()); return sb.toString(); } public static void bufferWriteFile(String filepath){ try{ File filename=new File(filepath); /** create newfile if doesn't exist,else pass */ if(!filename.exists()) { filename.createNewFile(); } try{ FileWriter writer=new FileWriter(filename); BufferedWriter bw= new BufferedWriter(writer); /** write content to buffer*/ bw.write(" Java is really awkward"); /** flush content from buffer to file */ bw.flush(); }catch (IOException f){ f.printStackTrace(); } }catch (IOException e){ e.printStackTrace(); } } /** Read jsonfile return jsonString */ public static String readJsonFile(String jsonpath){ StringBuffer sb=new StringBuffer(); try { FileReader reader = new FileReader(new File(jsonpath)); BufferedReader br=new BufferedReader(reader); String line =null; while((line=br.readLine())!=null){ sb.append(line); } }catch (IOException e){ e.printStackTrace(); } return sb.toString(); } /** get jsonobject attribute by alibaba fastjson .JsonObject*/ public static JSONObject jsonToJava(String jsonpath){ /** get json string from json file*/ String jsonString=readJsonFile(jsonpath); /** jsonString to jsonobject*/ JSONObject object = JSONObject .parseObject(jsonString); /** * value = object.get("key") System.out.println(object.toString()); String str=object.getString("string"); Boolean bool=object.getBoolean("boolean"); List<Object> list=JSONObject.parseArray(object.getJSONArray("list").toString(),Object.class); System.out.println(list); */ return object; } /** fastjson use: * 1.fastjson List转JSONArray * List<T> list = new ArrayList<T>(); * JSONArray array= JSONArray.parseArray(JSON.toJSONString(list)); * * * 2.fastjson JSONArray转List * JSONArray array = new JSONArray(); * List<EventColAttr> list = JSONObject.parseArray(array.toJSONString(), EventColAttr.class); * * * 3.fastjson 字符串转List * String str = ""; * List<T> list = JSONObject.parseArray(str,T.class); * @param jsonStr * @return */ /** denpendended by fastjson.JSON */ public static Map jsonStrToMap(String jsonStr){ // Map<String,Object> map = JSON.parseObject(jsonStr,Map.class); Map<String,Object> map = (Map)JSON.parse(jsonStr); System.out.println(map); return map; } /** 帕布里克,斯泰迪克沃伊得们,让世界从这里感受痛楚吧...*/ public static void main(String[] args) throws InterruptedException { String path = System.getProperty("user.dir") + "/src/testdir/"; String filename = "test.json"; jsonStrToMap(readJsonFile(path+filename)); } }