diff --git a/boot-service/src/main/java/com/xwbing/demo/CalendarDemo.java b/boot-service/src/main/java/com/xwbing/demo/CalendarDemo.java new file mode 100644 index 0000000..f673804 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/demo/CalendarDemo.java @@ -0,0 +1,83 @@ +package com.xwbing.demo; + +import java.util.Calendar; +import java.util.Date; + +/** + * 创建日期: 2017年2月16日 下午3:32:04 + * 作者: xiangwb + */ + +public class CalendarDemo { + public static void main(String[] args) { + Calendar calendar = Calendar.getInstance(); + Date date = calendar.getTime(); + calendar.setTime(date); + + + + /* + * 设置calendar,使其表示 2008-08-08 08:08:08 + */ + calendar.set(Calendar.YEAR, 2008);// 年 + calendar.set(Calendar.MONTH, 7);// 月从0开始,0表示1月 + /* + * 设置日 对应的时间分量常用的: DATE:月中天 DAY_OF-MONTH:月中的天,与DATE一致 + * DAY_OF_WEEK:周中的天,星期几 DAY_OF_YEAR:年中的天 + */ + calendar.set(Calendar.DAY_OF_MONTH, 8);// 日 + calendar.set(Calendar.HOUR_OF_DAY, 8);// 时 + calendar.set(Calendar.MINUTE, 8);// 分 + calendar.set(Calendar.SECOND, 8);// 秒 + System.out.println(calendar.getTime()); + /* + * int get(int field) 获取对应的分量的值 + */ + Calendar now = Calendar.getInstance(); + int year = now.get(Calendar.YEAR);// 获取年 + int month = now.get(Calendar.MONTH) + 1;// 获取月+1 + int day = now.get(Calendar.DATE);// 获取日 + int house = now.get(Calendar.HOUR);// 时 + int minute = now.get(Calendar.MINUTE);// 分 + int second = now.get(Calendar.SECOND);// 秒 + System.out.println(year + "-" + month + "-" + day + " " + house + ":" + minute + ":" + second); + + + // 查看星期几 + int week = now.get(Calendar.DAY_OF_WEEK); + System.out.println("周" + (week == 1 ? 7 : week - 1)); + // 当年过了几天 + int doy = now.get(Calendar.DAY_OF_YEAR); + System.out.println(year + "年已经过了" + doy + "天"); + // 当月共有多少天 + int days = now.getActualMaximum(Calendar.DAY_OF_MONTH); + System.out.println("本月共有" + days + "天"); + // 当年共有多少天 + int years = now.getActualMaximum(Calendar.DAY_OF_YEAR); + System.out.println("今年共有" + years + "天"); + // 查看今年2月份有几天 + now.set(Calendar.MONTH, 1); + System.out.println(now.getActualMaximum(Calendar.DAY_OF_MONTH)); + + + + + /* + * 查看3年2个月零8天以后的日期? + */ + Calendar nowTime = Calendar.getInstance(); + System.out.println(nowTime.getTime()); + nowTime.add(Calendar.YEAR, 3); + nowTime.add(Calendar.MONTH, 2); + nowTime.add(Calendar.DAY_OF_YEAR, 8);// 用DAY_OF_YEAR + System.out.println(nowTime.getTime()); + /* + * 当遇到类似开发需求: 要求用户输入一个日期,然后对该日期进行一系列的运算 再将计算后的日期显示给用户时。 流程如下: + * 1:获取用户输入的日期字符串 + * 2:使用SimpleDateFormat将其转换为Date + * 3:创建一个Calendar。使其表示Date表示的日期 + * 4:使用Calendar根据需求计算时间 + * 5:将Calendar转换为一个Date 6:使用SimpleDateFormal将Date转换为字符串后显示给用户 + */ + } +} diff --git a/boot-service/src/main/java/com/xwbing/demo/CollectionDemo.java b/boot-service/src/main/java/com/xwbing/demo/CollectionDemo.java new file mode 100644 index 0000000..56bd562 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/demo/CollectionDemo.java @@ -0,0 +1,204 @@ +package com.xwbing.demo; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; + +import java.util.*; + +/** + * 创建日期: 2017年2月16日 下午4:06:56 + * 作者: xiangwb + */ + +public class CollectionDemo { + public static void main(String[] args) { + /** + * 数组 + */ + int[] arr1 = new int[4]; + int[] arr2 = new int[]{1, 3, 5, 7}; + int[] arr3 = {12, 3, 5, 6, 2, 8, 9, 4}; + for (int i = 0; i < arr3.length - 1; i++) {//选择排序 + for (int j = i + 1; j < arr3.length; j++) { + if (arr3[i] > arr3[j]) { + int temp = arr3[i]; + arr3[i] = arr3[j]; + arr3[j] = temp; + } + } + } + for (int i = 0; i < arr3.length - 1; i++) {//冒泡排序 + for (int j = 0; j < arr3.length - 1 - i; j++) { + if (arr3[j] > arr3[j + 1]) { + int t = arr3[j]; + arr3[j] = arr3[j + 1]; + arr3[j + 1] = t; + } + } + } + /** + * 数组字符串操作 + */ + String[] arrays = {"1", "2", "3", "4"}; + List strings = Arrays.asList(arrays); + String arrayStr = JSONArray.toJSONString(strings);//数组字符串 + JSONArray jsonArray = JSON.parseArray(arrayStr);//转为JSONArray + jsonArray.add("5");//相应操作 + String jsonString = JSON.toJSONString(jsonArray);//转为数组字符串 + + /** + * 数组转集合 该集合表示原来的数组 对集合的操作就是对数组的操作,那么添加元素会导致原数组扩容, + * 那么就不能表示原来的数组了,会抛出UnsupportedOperationException异常 + */ + String[] array = {"one", "two", "three", "four"}; + List l = Arrays.asList(array); + /* + * 所有的集合提供了一个带有collection类型参数的构造方法 该构造方法称为:复制构造器 + * 作用是在创建当前集合的同时,集合中包含给定集合中的所有元素 + */ + List list1 = new ArrayList(l); + + /** + * 集合转数组 + */ + List lsit = new ArrayList(2); + lsit.add("guan"); + lsit.add("bao"); + String[] arrayy = new String[lsit.size()];// 大小为list.size() + /* + * toArray(T[] array): 若给定的数组可用(数组可以存放集合所有的元素)时 + * 则使用该数组,若不可用,会自动创建一个与给定数组同类型的数组 + */ + arrayy = lsit.toArray(arrayy); + + /** + * 基本api + */ + List list = new ArrayList();// 有序 + list.add(1); + list.add(0, 0);// 元素插入到指定位置 + list.add(2); + list.add(3); + list.add(5); + list.add(4); + list.add(6); + System.out.println(list); + Integer old = list.set(1, 11);// 替换元素,返回值为原位置的元素 + Integer one = list.get(0);// 获取下标元素 + list.remove(Integer.valueOf(6)); + list.remove(0);// 从集合中删除指定位置的元素,并将其返回 + int size = list.size();// 长度 + boolean isEmpty = list.isEmpty();// 是否为空 + boolean contains = list.contains(Integer.valueOf(1));// 是否包含元素 + // l.clear();//清除集合元素 + Set s = new HashSet();// 无序 + s.add(111); + s.add(222); + s.add(333); + list.addAll(s);// 添加集合 + contains = list.containsAll(s);// 是否包含集合 + list.removeAll(s);// 清除共有的元素 + System.out.println(list); + /** + * ArrayList的subList结果不可强转成ArrayList 子集,含头不含尾,对子集的修改,就是原集合相应的内容 + */ + List subList = list.subList(0, 1); + list.subList(0, 1).clear();// 删除集合中0-1的元素 + Collections.sort(list);// 对集合进行从小到大排序 + Collections.reverse(list);// 反转 + System.out.println(list); + + /** + * 新循环foreach遍历集合,编译器会将它改为迭代器方式遍历, 所以在使用新循环遍历集合时,不能通过集合的方法增删元素 + */ + for (Integer o : list) { + // list.remove(o); + } + /** + * lambda表达式 + */ + list.forEach(o -> System.out.println(o)); + + /** + * 迭代器 + */ + Iterator it = list.iterator();// 获取用于遍历当前集合的迭代器 + while (it.hasNext()) { + Integer str = it.next(); + if (1 == str) { + /* + * 在使用迭代器遍历集合时,不要使用集合的方法曾删元素,否则会引发异常 + */ + // list.remove(str); + it.remove(); + } + } + + /** + * 自定义排序 推荐匿名内部类形式创建比较器 + */ + Comparator com = new Comparator() {// 返回正数,零,负数各代表大于,等于,小于 + public int compare(Integer o1, Integer o2) { + return o2 - o1; + } + }; + Collections.sort(list, com); + System.out.println(list); + /** + * lambda表达式 + */ + list.sort((o1, o2) -> o1 - o2); + + /* + * 队列 队列也可以存放一组元素,但是存取元素必须 遵循:先进先出原则 + * linkedlist也实现类队列接口,因为它可以保存一组元素,并且首尾增删块快,正好符合队列特点 + */ + Queue queue = new LinkedList(); + queue.offer("one");// 入队操作,向队尾追加一个新元素 + queue.offer("two"); + queue.offer("three"); + queue.offer("four"); + System.out.println(queue); + String str = queue.poll();// 出队操作,从队首获取元素,获取后该元素就从队列中被删除了 + System.out.println(str); + System.out.println(queue); + str = queue.peek();// 引用队首元素,但是不做出队操作 + System.out.println(str); + System.out.println(queue); + System.out.println("遍历开始"); + System.out.println("lenth:" + queue.size()); + /* + * 遍历从后往前 因为size一直在变,从前往后会没取完 + */ + // for (int i = queue.size(); i >0; i--) { + // str=queue.poll(); + // System.out.println(str); + // } + while (queue.size() > 0) { + str = queue.poll(); + System.out.println(str); + } + System.out.println("遍历结束"); + System.out.println(queue); + + /** + * 栈 存储一组元素,但是存取元素必须遵循先进后出原则 通常为了实现后退这类功能时会使用栈 + */ + /* + * java.util.Deque 双端队列,两端都可以进出队 当只调用从一端进出对操作时,就形成了栈结构 因此,双端队列为栈提供类两个方法: + * push ,pop + */ + Deque stack = new LinkedList(); + stack.push("one");// 入栈操作,最后入栈的元素在栈顶(第一个元素位置) + stack.push("two"); + stack.push("three"); + stack.push("four"); + System.out.println(stack); + str = stack.poll();// 出栈操作,第一个元素先出 + System.out.println(str); + System.out.println(stack); + str = stack.peek();// 引用队首元素,但是不做出队操作 + System.out.println(str); + System.out.println(stack); + } +} diff --git a/boot-service/src/main/java/com/xwbing/demo/CreateOrderNoDemo.java b/boot-service/src/main/java/com/xwbing/demo/CreateOrderNoDemo.java new file mode 100644 index 0000000..941ea3e --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/demo/CreateOrderNoDemo.java @@ -0,0 +1,55 @@ +package com.xwbing.demo; + +import org.apache.commons.collections.CollectionUtils; + +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +/** + * 说明: 订单编号生成 + * 创建日期: 2017年3月24日 下午5:06:37 + * 作者: xiangwb + */ + +public class CreateOrderNoDemo { + public synchronized static String getNo() { + String sequence = ""; + SimpleDateFormat sdf = new SimpleDateFormat("YYYY_MM_DD"); + String date = sdf.format(new Date()); + StringBuffer sql = new StringBuffer("select * from order_table"); + sql.append(" where order_no like '" + date + "%'"); + sql.append(" order by create_time desc"); + List list=queryList(); + if(CollectionUtils.isNotEmpty(list)){ + String orderNo = list.get(0).getOrderNo(); + long newOrderNo = Long.valueOf(orderNo.substring(8, 18)) + 1; + String sequ = new DecimalFormat("0000000000").format(newOrderNo); + sequence = date + sequ; + }else { + sequence = date + "0000000000"; + } + return sequence; + } + class Order{//模拟订单类 + String orderNo; + + public String getOrderNo() { + return orderNo; + } + + public void setOrderNo(String orderNo) { + this.orderNo = orderNo; + } + + } + public static List queryList(){//模拟查询 + return null; + } + public static void main(String[] args) { + long a=12356; + String sequ = new DecimalFormat("0000000000").format(a); + System.out.println(sequ); + } +} diff --git a/boot-service/src/main/java/com/xwbing/demo/FileDemo.java b/boot-service/src/main/java/com/xwbing/demo/FileDemo.java new file mode 100644 index 0000000..53d0fe1 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/demo/FileDemo.java @@ -0,0 +1,68 @@ +package com.xwbing.demo; + +import org.springframework.core.io.ClassPathResource; + +import java.io.File; +import java.io.IOException; + +/** + * 说明: java.io.File File的每一个实例可以表示文件系统中的一个文件或目录 使用file可以: + * 1:访问文件或目录的属性(如:大小,名字,修改时间等) 2;操作文件或目录(创建,删除文件和目录) 3:访问目录中的所有内容 但是不可以 访问文件数据 + * 创建日期: 2017年2月17日 下午2:26:18 + * 作者: xiangwb + */ + +public class FileDemo { + public static void main(String[] args) throws IOException { + /* + * + * 文件 + * 尽量使用相对路径 + * 在eclipse中,"."当前目录,指的是 + * 项目的根目录 + */ + //创建文件对象 + File file = new File("." + File.separator + "demo.txt");//创建文件对象,并不创建文件 + if(!file.exists()){ + file.createNewFile(); //创建文件 + } + if(file.exists()){ + file.delete();//删除文件 + } + String name = file.getName();//获取文件名 + long length = file.length();//获取文件大小 + long time = file.lastModified();//获取文件最后修改时间 + //查看文件是否具有可运行,可读,可写的权限 + boolean b=file.canExecute(); + boolean b1=file.canRead(); + boolean b2=file.canWrite(); + boolean isDir = file.isDirectory();//是否为一个目录 + boolean isFile = file.isFile();//是否为一个文件 + boolean isHidden=file.isHidden();//是否为一个隐藏文件 + + /** + * 目录 + */ + File dir=new File("demo"); + File[] subs=dir.listFiles();//获取目录下的所有子项 + if(!dir.exists()){ + dir.mkdir(); + }else { + dir.delete();//空目录才能删除 + } + File dirs =new File("a"+File.separator+"b"+File.separator+"c"); + if(!dirs.exists()){ + /* + * 在创建当前目录的同时将不存在的父目录一并创建出来 + */ + dirs.mkdirs(); + } + /** + * 获取路径 + * java resources 编译后在WEB-INF/classes下 同级 + */ + String tomcatHome = System.getProperty("catalina.home");//服务器tomcat路径 + ClassPathResource pic = new ClassPathResource("conf");//获取classes下conf文件夹路径 + String absolutePath = pic.getFile().getAbsolutePath(); + } +} diff --git a/boot-service/src/main/java/com/xwbing/demo/ForEachMap.java b/boot-service/src/main/java/com/xwbing/demo/ForEachMap.java new file mode 100644 index 0000000..ed7f073 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/demo/ForEachMap.java @@ -0,0 +1,78 @@ +package com.xwbing.demo; + + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * 遍历map + * 三种方式: + * 遍历所有的key + * 遍历所有的key-value对 + * 遍历所有的value(相对不常用) + * + * @author xiangwb + * + */ +public class ForEachMap { + public static void main(String[] args) { + Map map=new HashMap(); + map.put("语文", 99); + map.put("数学", 98); + map.put("英语", 97); + map.put("物理", 96); + map.put("化学", 99); + System.out.println(map); + + + + /* + * 遍历所有的key + * set keySet() + * 该方法会将当前map中所有的key存入一个set集合后返回 + * 那么遍历该集合就等于遍历类所有的key + */ + Set keySet=map.keySet(); + for(String key:keySet){ + System.out.println(key); + } + + /* + * 遍历每一组键值对(推荐) + * map中每一组键值对都是由map的内部类: + * java.util.map.entry的一个实例类表示的 + * entry有两个方法:getkey getvalue 可以分别获取这一组键值对中的key和value + * + * Set entrySet + * 该方法会将map中的每一组键对(entry实例) + * 存入一个set集合后返回 + */ + Set> entrySet=map.entrySet(); + for(Entry e:entrySet){ + String key=e.getKey(); + Integer value=e.getValue(); + System.out.println(key+":"+value); + } + + /* + * 遍历所有的value + * Collection values() + * 该方法会将当前map中所有的value存入一个集合后返回 + */ + Collection values=map.values(); + for(Integer value:values){ + System.out.println(value); + } + + + /** + * jdk1.8 + */ + map.forEach((k,v)->{ + System.out.println("key : " + k + "; value : " + v); + }); + } +} diff --git a/boot-service/src/main/java/com/xwbing/demo/IODemo.java b/boot-service/src/main/java/com/xwbing/demo/IODemo.java new file mode 100644 index 0000000..0986fbb --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/demo/IODemo.java @@ -0,0 +1,105 @@ +package com.xwbing.demo; + +import java.io.*; + +/** + * 创建日期: 2017年2月20日 上午10:12:20 + * 作者: xiangwb + */ + +public class IODemo { + public static void main(String[] args) throws Exception { + /** + * GBK:国标编码,中文占2字节 + * UTF-8:unicode的子集,其中文占3个字节 + * ISO8859-1:欧洲编码集,不支持中文 + */ + + /** + * 写 + */ + FileOutputStream fos = new FileOutputStream("fos.txt", true);//追加写模式 + fos.write("你好".getBytes("gbk")); + System.out.println("写出完毕"); + fos.close();//关闭流 + + /** + * 读 + */ + FileInputStream fis = new FileInputStream("fos.txt"); + byte[] data = new byte[1024 * 10]; + int len = fis.read(data);//数据读入data里 + String str = new String(data, 0, len, "gbk"); + fis.close(); + + InputStream is = new ByteArrayInputStream(str.getBytes("gbk")); + byte[] da = new byte[is.available()]; + is.read(da); + is.close(); + /** + * 缓冲流 + * + */ + BufferedOutputStream bos = new BufferedOutputStream(fos); + bos.write("你好".getBytes()); + bos.close();//close前会自动flush,关流只需管最外层高级流 + + /** + * 使用缓冲流的形式复制文件 + */ + BufferedInputStream bis1 = new BufferedInputStream(fis); + BufferedOutputStream bos1 = new BufferedOutputStream(fos); + int d ; + while ((d = bis1.read()) != -1) { + bos1.write(d); + } + bis1.close(); + bos1.close(); + + /* + * 字符流 + * 读写单位是字符 + * 可以按照指定的字符集,将写出的字符转换为对应的字节 + * 字符流只适合读写文本数据 + * 转码 + *uft-8转gbk + */ + InputStreamReader isr = new InputStreamReader(fis, "utf-8"); + OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk"); + int leng = 1; + while ((leng = isr.read()) != -1) { + osw.write(leng); + } + osw.close(); + isr.close(); + + /** + * 缓冲字符输入流,特点:读取速度快,并且可以按行读取字符串 + */ + BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("fis.txt"))); + String line = null; + //readerLIne():连续读取若干字符,知道遇到换行符为止,该字符串中不包含换行符 + while ((line = br.readLine()) != null) { + //TODO + } + br.close(); + + /** + * 缓冲字符输出流 + */ + PrintWriter pw = new PrintWriter("e.txt", "utf-8");//PrintWriter可以直接创建基于文件进行写操作 + + FileOutputStream fos1 = new FileOutputStream("pw1.txt"); + OutputStreamWriter osw1 = new OutputStreamWriter(fos, "utf-8");//可以指定字符 + PrintWriter pw1 = new PrintWriter(osw, true);///////当第一个参数为流,可以使用第二个参数来指定是否自动flush + pw1.println("......"); + pw1.close(); + + + /** + * 读取配置文件的2种方式 + */ + String filePath = IODemo.class.getResource("/conf/jdbc.properties").getPath(); + InputStream in = IODemo.class.getResourceAsStream("/conf/jdbc.properties"); + } +} diff --git a/boot-service/src/main/java/com/xwbing/demo/Java8DateDemo.java b/boot-service/src/main/java/com/xwbing/demo/Java8DateDemo.java new file mode 100644 index 0000000..d39e022 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/demo/Java8DateDemo.java @@ -0,0 +1,87 @@ +package com.xwbing.demo; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.Month; +import java.time.MonthDay; +import java.time.Year; +import java.time.YearMonth; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.Date; + +/** + * 说明: + * 项目名称: zxwbing + * 创建日期: 2017年3月29日 下午4:37:09 + * 作者: xiangwb + */ + +public class Java8DateDemo { + public static void main(String[] args) { + DateTimeFormatter formatted = DateTimeFormatter.ofPattern("YYYY-MM-dd"); + LocalDate date = LocalDate.now();// Current Date + String dstr = date.format(formatted);// 格式化 + date = LocalDate.parse(dstr, formatted);// 解析 + LocalDate firstDay2017 = LocalDate.of(2017, 1, 1);// 2017-01-01 + LocalDate hundredDay2017 = LocalDate.ofYearDay(2017, 100);// 2017-03-29 + System.out.println(firstDay2017.equals(hundredDay2017));// 比较时间是否相等 + LocalDate todayKolkata = LocalDate.now(ZoneId.of("Asia/Kolkata")); + int year = date.getYear();// 获取年 + int month = date.getMonthValue(); // 获取月 + int day = date.getDayOfMonth(); // 获取日 + date.isLeapYear();// 是否为闰年 + LocalDate dateOfBirth = LocalDate.of(2010, 05, 11); + MonthDay monthDay = MonthDay.now(); + MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), + dateOfBirth.getDayOfMonth());// 月日 + YearMonth yearMonth = YearMonth.of(2018, 8);// 年月 + Year yearr = Year.now(); + LocalDate nextYear = date.plusYears(1); // 1年后日期,可以一个月,一年,一小时,一分钟 + LocalDate beforYear = date.minusYears(1);// 1年前日期,可以一个月,一年,一小时,一分钟 + System.out.println(nextYear.isBefore(beforYear)); // 判断某个日期是在另一个日期的前面还是后面 + + LocalTime time = LocalTime.now();// Current Time + LocalTime specificTime = LocalTime.of(12, 0, 0);// 12:20:25 + LocalTime newSpecificTime = specificTime.plusHours(2);// 增加2小时 + LocalTime timeKolkata = LocalTime.now(ZoneId.of("Asia/Kolkata")); + LocalTime specificSecondTime = LocalTime.ofSecondOfDay(1);// 00:00:01 + + LocalDateTime dateTime = date.atTime(time);// Create LocalDateTime from + // LocalDate + LocalDateTime today = LocalDateTime.now();// Current Date + today = LocalDateTime.of(LocalDate.now(), LocalTime.now()); + LocalDateTime specificDate = LocalDateTime.of(2014, Month.JANUARY, 1, + 10, 10, 30);// 2014-01-01T10:10:30 + LocalDateTime todayKolkata1 = LocalDateTime.now(ZoneId + .of("Asia/Kolkata")); + int second=today.getSecond();//获取时间中的秒 + int week=today.getDayOfWeek().getValue();//获取周几 + + /* + * 时钟 + */ + Clock clock = Clock.systemUTC(); + System.out.println(clock.millis());// 当前毫秒数 + Instant in = clock.instant(); + LocalDate d = LocalDate.now(clock); + Instant timestamp = Instant.now();// 类似于java.util.Date + /* + *新旧日期转换 + */ + Instant instant = new Date().toInstant(); + Date dateee = Date.from(instant); + + /* + * 时间相差 + */ + LocalDateTime be = LocalDateTime.of(2016, 2, 11, 10, 30); + LocalDateTime af = LocalDateTime.of(2016, 3, 11, 10, 30); + Duration duration = Duration.between(be, af); + System.out.println(duration.toDays() + duration.toHours()); + } +} \ No newline at end of file diff --git a/boot-service/src/main/java/com/xwbing/demo/JsonDemo.java b/boot-service/src/main/java/com/xwbing/demo/JsonDemo.java new file mode 100644 index 0000000..550862f --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/demo/JsonDemo.java @@ -0,0 +1,118 @@ +package com.xwbing.demo; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; +import com.google.gson.*; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.xwbing.domain.entity.sys.BaseEntity; +import com.xwbing.domain.entity.sys.SysUser; +import com.xwbing.util.RestMessage; +import lombok.Data; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 创建日期: 2017年3月18日 下午1:34:05 + * 作者: xiangwb + */ +@Data +public class JsonDemo { + /* + * fastJson注解 + */ + @JSONField(serialize = false) + private String name; + @JSONField(name = "nick_name") + private String nickName; + /* + * gson注解 + */ + @SerializedName("user_age") + @Expose //可以序列化和反序列化 + private String userAge; + @Expose(serialize = false)//临时字段,可以反序列化 + private String addr; + @Expose + private String email; + + public static void main(String[] args) { + /** + * fastJson + */ + String jsonStr = "{'id':'888888','resultMessage':{'msg':'200','isSuccess':'true'}}"; + Map map = new HashMap<>(); + map.put("id", "99999"); + List list = new ArrayList<>(); + /* + * to jsonObject + */ + JSONObject jsonObject = new JSONObject(map);// map转JSONObject + jsonObject = JSONObject.parseObject(jsonStr);// json字符串转JSONObject + /* + * to javaObject + */ + BaseEntity entiry = JSONObject.toJavaObject(jsonObject, + BaseEntity.class);//jsonObject转javaObject + entiry = JSONObject.parseObject(jsonStr, BaseEntity.class);// json字符串转javaObject + /* + * JSONArray <--> list + */ + String arrayStr = JSONArray.toJSONString(list); + list = JSONArray.parseArray(arrayStr, SysUser.class); + /* + * to object + */ + Object obj = JSONObject.toJSON(entiry);// javabean转object + /* + * to jsonStr + */ + jsonStr = JSONObject.toJSONString(entiry); + /* + * 获取jsonObject属性 + */ + String id = jsonObject.getString("id"); + RestMessage result = JSONObject.toJavaObject( + jsonObject.getJSONObject("resultMessage"), RestMessage.class); + + /** + * gson + */ + Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().serializeNulls().create();//不导出实体中没有用@Expose注解的属性,并把null值也转换 + JsonDemo jsonDemo = new JsonDemo(); + jsonDemo.setUserAge("18"); + jsonDemo.setAddr("西溪湿地"); + String serialize = gson.toJson(jsonDemo); + String s = new Gson().toJson(jsonDemo); + JsonDemo deserialize = gson.fromJson(s, JsonDemo.class); + + + String gsonStr = "{'name':'John', 'sex':1,'role':{'id':'33'}}"; + /* + * jsonStr to JsonElement + */ + JsonElement jsonElement = new JsonParser().parse(gsonStr); + /* + * jsonStr to javaObject + */ + SysUser user = new Gson().fromJson(gsonStr, SysUser.class); + /* + * JsonElement to javaObject + */ + user = new Gson().fromJson(jsonElement, SysUser.class); + /* + * javaObject to jsonStr + */ + gsonStr = new Gson().toJson(user); + /* + * 获取属性 + */ + JsonObject gsonObject = jsonElement.getAsJsonObject(); + JsonElement role = jsonElement.getAsJsonObject().get("role"); + String name = jsonElement.getAsJsonObject().get("name").getAsString(); + } +} diff --git a/boot-service/src/main/java/com/xwbing/demo/LambdaDemo.java b/boot-service/src/main/java/com/xwbing/demo/LambdaDemo.java new file mode 100644 index 0000000..cb61e06 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/demo/LambdaDemo.java @@ -0,0 +1,112 @@ +package com.xwbing.demo; + +import com.xwbing.domain.entity.sys.SysUser; +import com.xwbing.domain.entity.sys.SysUserRole; +import com.xwbing.service.sys.SysUserRoleService; +import com.xwbing.service.sys.SysUserService; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import javax.annotation.Resource; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +/** + * Date: 2017/6/15 17:09 + * Author: xiangwb + */ +public class LambdaDemo { + @Resource + private SysUserRoleService sysUserRoleService; + @Resource + private static ThreadPoolTaskExecutor taskExecutor; + + public static void main(String[] args) { + //匿名内部类 + Thread t = new Thread(() -> System.out.println("hello,lambda")); + t.start(); + List list = Arrays.asList("a", "b", "c"); + list.sort(Comparator.naturalOrder()); + + /** + * stream api 高级版本的迭代器 + */ + List lists = Arrays.asList(1, 2, 4, 2, 3, 5, 5, 6, 8, 9, 7, 10); +// //遍历 +// Arrays.stream(arrays).forEach(System.out::println); + list.forEach(System.out::println); + System.out.println("sort:" + lists.stream().sorted((o1, o2) -> o2 - o1).collect(Collectors.toList()));//排序 + System.out.println("map:" + lists.stream().map(o1 -> o1 * 2).collect(Collectors.toList()));//转换 + System.out.println("distinct:" + lists.stream().distinct().collect(Collectors.toList()));//去重(去重逻辑依赖元素的equals方法) + System.out.println("limit:" + lists.stream().limit(4).collect(Collectors.toList()));//截取 + System.out.println("skip:" + lists.stream().skip(4).collect(Collectors.toList()));//丢弃 + //过滤 + System.out.println("filter:" + lists.stream().filter(o1 -> o1 > 3 && o1 < 8).collect(Collectors.toList())); + Predicate gt = integer -> integer > 3;//函数式接口Predicate + Predicate lt = integer -> integer < 8; + System.out.println("重用filter:" + lists.stream().filter(gt.and(lt)).collect(Collectors.toList())); + //聚合 + System.out.println("reduce:" + lists.stream().reduce((o1, o2) -> o1 + o2).get());//聚合 + System.out.println("reduce:" + lists.stream().reduce(0, (o1, o2) -> o1 + o2));//聚合(给定默认值) + System.out.println("ids:" + list.stream().reduce((sum, item) -> sum + "," + item).get());//常用//list(a,b,c)-->,a,b,c-->a,b,c + System.out.println("ids:" + list.stream().reduce("", (sum, item) -> sum + "," + item).substring(1)); + String s = list.stream().reduce("", (sum, item) -> sum + "'" + item + "',");//list(a,b,c)-->'a','b','c',-->'a','b','c' + System.out.println("id in:" + s.substring(0, s.lastIndexOf(","))); + //join + System.out.println("join:" + list.stream().collect(Collectors.joining(",")));//list(a,b,c)-->a,b,c + System.out.println("join:" + String.join(",", list)); + //统计 + IntSummaryStatistics statistics = lists.stream().mapToInt(x -> x).summaryStatistics(); + System.out.println("List中最大的数字 : " + statistics.getMax()); + System.out.println("List中最小的数字 : " + statistics.getMin()); + System.out.println("所有数字的总和 : " + statistics.getSum()); + System.out.println("所有数字的平均值 : " + statistics.getAverage()); + System.out.println("List成员个数 : " + statistics.getCount()); + //all example + System.out.println("all:" + lists.stream().filter(Objects::nonNull).distinct().mapToInt(num -> num * 2).skip(2).limit(4).sum()); + //遍历list存入map里 + Map userMap = new SysUserService().listAll().stream().collect(Collectors.toMap(SysUser::getId, Function.identity())); + //分组 + Map> groupMap = new SysUserService().listAll().stream().collect(Collectors.groupingBy(SysUser::getSex));//(分组条件为key,分组成员为value) + //非空判断 + Optional optional = list.stream().reduce((sum, item) -> sum + "," + item); + String reduce; + if (optional.isPresent()) { + reduce = optional.get(); + } + //异步回调 + CompletableFuture> future = CompletableFuture.supplyAsync(LambdaDemo::getList, taskExecutor); + try { + List sysUsers = future.get(); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + } + + /** + * filter + * + * @return + */ + public List getRoleUsers(int flag) { + if (flag == 0) {//例一 + Predicate roles = sysUser -> { + List sysUserRoles = sysUserRoleService.listByUserId(sysUser.getId()); + return sysUserRoles.size() > 0; + }; + return new ArrayList().stream().filter(roles).collect(Collectors.toList()); + } else {//例二 + return new ArrayList().stream().filter(sysUser -> { + List sysUserRoles = sysUserRoleService.listByUserId(sysUser.getId()); + return sysUserRoles.size() > 0; + }).collect(Collectors.toList()); + } + } + + public static List getList() { + return null; + } +} diff --git a/boot-service/src/main/java/com/xwbing/demo/RecursiveFIle.java b/boot-service/src/main/java/com/xwbing/demo/RecursiveFIle.java new file mode 100644 index 0000000..2a275d3 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/demo/RecursiveFIle.java @@ -0,0 +1,29 @@ +package com.xwbing.demo; + +import java.io.File; + +/** + * 删除一个含有子项的目录 + * + * @author xiangwb + * + */ +public class RecursiveFIle { + public static void main(String[] args) { + File dir = new File("C:\\Users\\admin\\Desktop\\123"); + deleteFile(dir); + } + /* + * 将给定的file表示的文件或目录删除 + */ + public static void deleteFile(File f) { + if(f.isDirectory()){ + //将该目录下的所有子项删除 + File[] subs=f.listFiles(); + for(File sub:subs){ + deleteFile(sub); + } + } + f.delete(); + } +} diff --git a/boot-service/src/main/java/com/xwbing/demo/StringDemo.java b/boot-service/src/main/java/com/xwbing/demo/StringDemo.java new file mode 100644 index 0000000..8f8029f --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/demo/StringDemo.java @@ -0,0 +1,89 @@ +package com.xwbing.demo; + +import java.text.MessageFormat; +import java.util.Scanner; + +/** + * 创建日期: 2017年2月16日 下午5:27:23 + * 作者: xiangwb + */ + +public class StringDemo { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.println("请输入:"); + String strr = sc.next(); + System.out.println(strr); + + /** + * 基本语法 + */ + String str = "thinking in java"; + str.trim();// 去除当前字符两边的空格 + str.toUpperCase();// 转换为全大写 + str.toLowerCase();// 转换为全小写 + boolean contains = str.contains("ss");//判断是否包含某字符 + int index = str.indexOf("in");// 查找in在str字符串中的位置,若没有返回-1 + index = str.indexOf("in", 3);// 从指定位置处开始查找 + index = str.lastIndexOf("in");// 最后一次出现位置 + char c = str.charAt(5);// 获取当前字符串指定下标对应的位置 + boolean starts = str.startsWith("thi");// 判断当前字符串是否是以指定的字符串开始 + boolean ends = str.endsWith("ava");// 判断当前字符串是否是以指定的字符串结尾 + String sub = str.substring(5, 9);// 子集,含头不含尾 + sub = str.substring(1);// 指定位置到末尾 + System.out.println(sub); + + /** + * 正则表达式:匹配 + */ + String regex = "[a-zA-Z0-9_]+@[a-zA-Z0-9_]+(\\.[a-z]+)+"; + String mail = "fancq@tedu.cn.cn"; + boolean flag = mail.matches(regex); + if (flag) { + System.out.println("是邮箱"); + } else { + System.out.println("不是邮箱"); + } + + /** + * 正则表达式:分割 + */ + String imagName = "1.jpg"; + String names[] = imagName.split("\\."); + imagName = System.currentTimeMillis() + "." + names[1]; + System.out.println(imagName); + + /** + * 正则表达式:替换 + */ + String imgName = "1.jpg"; + imgName = imgName.replaceAll(".+\\.", System.currentTimeMillis() + "."); + System.out.println(imgName); + + /** + * StringBuilder + */ + String sstr = "努力学习java"; + StringBuilder b = new StringBuilder(sstr); + b.append(",为了找好工作"); + System.out.println(b.toString()); + b.replace(9, 16, "就是为了改变世界"); + System.out.println(b.toString()); + b.delete(0, 9); + System.out.println(b.toString()); + b.insert(0, "活着,"); + System.out.println(b.toString()); + + /** + * 判断日期字符串大小 >0 =0 <0 + */ + int n = "2018-08-08 08:08:08".compareTo("2018-08-08 08:08:09"); + System.out.println(n >= 0); + + /** + * 格式化字符串 + */ + System.out.println(String.format("xwbing %s", "项伟兵")); + System.out.println(MessageFormat.format("xwbing {0}", "项伟兵")); + } +} diff --git a/boot-service/src/main/java/com/xwbing/demo/ThreadDemo.java b/boot-service/src/main/java/com/xwbing/demo/ThreadDemo.java new file mode 100644 index 0000000..22c8b72 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/demo/ThreadDemo.java @@ -0,0 +1,138 @@ +package com.xwbing.demo; + + +import com.xwbing.util.DateUtil2; + +import java.util.Date; + +/** + * 创建日期: 2017年2月20日 上午11:32:55 + * 作者: xwb + */ + +public class ThreadDemo { + public static void main(String[] args) { + /** + * 直接继承thread并重写run方法,在其中定义当前线程要执行的任务 + * 缺点: + * 1:由于要求继承thread类,那么在将来项目中,就有可能出现继承冲突, + * 很多时候我们需要继承项目中的一个父类来复用方法,但是当前类又要继承thread作为线程去使用 java是单继承的,这里产生类冲突 + * 2:由于继承了thread后需要重写run方法来定义线程要执行的任务,这就导致线程与任务有一个强耦合关系 + * 当前线程就只能做run方法定义的任务,其他事情做不了,这不利于线程的重用 + */ + Thread t1 = new MyThread(); + t1.start();// 启动线程要调用start方法 + + /** + * 定义一个类并实现runable接口来单独定义线程要执行的任务 + */ + Runnable r1 = new MyRunnable(); + Thread t2 = new Thread(r1); + t2.start(); + + /** + * 使用匿名内部类实现两种创建线程的方式 + */ + // 方式一: + Thread thread1 = new Thread() { + public void run() { + // TUDO + } + }; + // 方式二: + Runnable runnable = new Runnable() { + public void run() { + Thread.yield();////模拟cpu时间片耗尽,线程发生切换 + } + }; + Thread thread2 = new Thread(runnable); + // 方式三:匿名对象方式(推荐) + Thread thread3 = new Thread(new Runnable() {// 使用sleep阻塞,实现电子表功能 + public void run() { + while (true) { + System.out.println(DateUtil2.dateToStr(new Date(),DateUtil2.YYYY_MM_DD_HH_MM_SS)); + try { + Thread.sleep(1000);// 线程进入n毫秒阻塞状态 + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + }); + + /** + * 获取线程相关信息的api + */ + Thread main = Thread.currentThread();// 获取的就是运行该方法的线程 + long id = main.getId();// 线程id + String name = main.getName();// 获取名字 + int priority = main.getPriority();// 查看优先级 + boolean isAlive = main.isAlive();// 是否还活着 + boolean isDaemon = main.isDaemon();// 是否为守护线程 + /** + * 设置线程优先级: 1最低,5为默认,10最高, + */ + thread1.setPriority(10); + thread3.setPriority(1); + thread1.start(); + thread2.start(); + thread3.start(); + + /** + * void setDaemon(boolean on) + * 后台线程,又叫做守护线程 当一个进程中的所有前台线程都结束了,进程就会结束 + * 无论进程中的其他后台线程是否还在运行,都要被强制中断。 + */ + Thread rose = new Thread() {// 前台线程 + public void run() { + } + }; + Thread jack = new Thread() {// 后台线程 + public void run() { + } + }; + // 设置为后台线程,需要在start前调用 + jack.setDaemon(true); + rose.start(); + jack.start(); + } +} + +/** + * void join() + * 线程提供了一个方法join,该方法允许一个线程在另一个线程上等待, 直到它的工作结束,才继续当前线程的后续工作 + * 否则一致处于阻塞状态 + */ +class Join { + public static void main(String[] args) { + final Thread t1 = new Thread() { + public void run() { + //一些耗时的操作 + } + }; + Thread t2 = new Thread() { + public void run() { + try { + t1.join();//这里t2线程会开始阻塞,直到t1线程的run方法执行完毕 + } catch (InterruptedException e) { + e.printStackTrace(); + } + //以下是当前线程的任务代码,只有t1线程运行完毕才会运行。 + } + }; + t1.start(); + t2.start(); + } +} + +class MyThread extends Thread { + public void run() {// run方法是线程要执行的任务 + // TUDO + } +} + +class MyRunnable implements Runnable { + public void run() { + // TUDO + } +} \ No newline at end of file diff --git a/boot-service/src/main/java/com/xwbing/demo/ThreadProducerConsumer.java b/boot-service/src/main/java/com/xwbing/demo/ThreadProducerConsumer.java new file mode 100644 index 0000000..2bef286 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/demo/ThreadProducerConsumer.java @@ -0,0 +1,99 @@ +package com.xwbing.demo; + +/** + * 创建日期: 2017年2月20日 下午4:03:56 + * 作者: xiangwb + */ + +public class ThreadProducerConsumer { + public static void main(String[] args) { + PublicResource resource = new PublicResource(); + new Thread(new ProducerThread(resource)).start(); + new Thread(new ConsumerThread(resource)).start(); + } +} + +/** + * 公共资源类 + */ +class PublicResource { + private int number = 9; + + /** + * 增加公共资源 + */ + public synchronized void increace() { + while (number != 0) { + try { + wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + number++; + System.out.println(number); + notifyAll(); + } + + /** + * 减少公共资源 + */ + public synchronized void decreace() { + while (number == 0) { + try { + wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + number--; + System.out.println(number); + notifyAll(); + } +} + +/** + * 生产者线程,负责生产公共资源 + */ +class ProducerThread implements Runnable { + private PublicResource resource; + + public ProducerThread(PublicResource resource) { + this.resource = resource; + } + + @Override + public void run() { + for (int i = 0; i < 10; i++) { + try { + Thread.sleep((long) (Math.random() * 1000)); + } catch (InterruptedException e) { + e.printStackTrace(); + } + resource.increace(); + } + } +} + +/** + * 消费者线程,负责消费公共资源 + */ +class ConsumerThread implements Runnable { + private PublicResource resource; + + public ConsumerThread(PublicResource resource) { + this.resource = resource; + } + + @Override + public void run() { + for (int i = 0; i < 10; i++) { + try { + Thread.sleep((long) (Math.random() * 1000)); + } catch (InterruptedException e) { + e.printStackTrace(); + } + resource.decreace(); + } + } +} diff --git a/boot-service/src/main/java/com/xwbing/demo/ThreadSyncDemo.java b/boot-service/src/main/java/com/xwbing/demo/ThreadSyncDemo.java new file mode 100644 index 0000000..06fa126 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/demo/ThreadSyncDemo.java @@ -0,0 +1,159 @@ +package com.xwbing.demo; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + + + +/** + * 说明: + * 多线程并发安全问题 + * 当多个线程访问同个资源时,由于线程切换的不确定性, + * 可能导致代码逻辑上的混乱,严重时可能导致系统崩溃 + * 项目名称: zdemo + * 创建日期: 2017年2月20日 下午2:34:05 + * 作者: xiangwb + */ + +public class ThreadSyncDemo { + public static void main(String[] args) { + /* + * 同步代码块 + */ + final Shop s=new Shop();//保证对象一致 + Thread t1=new Thread(){ + public void run(){ + s.buy(); + } + }; + Thread t2=new Thread(){ + public void run(){ + s.buy(); + } + }; + t1.start(); + t2.start(); + + + /* + * 静态方法锁 + */ + Thread tt1=new Thread(){ + public void run(){ + dosome(); + } + }; + Thread tt2=new Thread(){ + public void run(){ + dosome(); + } + }; + tt1.start(); + tt2.start(); + + /* + * 互斥 + */ + final Foo f=new Foo();//保证对象一致 + Thread ttt1=new Thread(){ + public void run(){ + f.methodA(); + } + }; + Thread ttt2=new Thread(){ + public void run(){ + f.methodB(); + } + }; + ttt1.start(); + ttt2.start(); + + /** + * arraylist,linkedlist,hashset都不是线程安全的 + * 线程安全的list集合有一个vector + * hashmap不是线程安全的,线程安全的是hashtable + * collections提供类相应的静态方法,可以将现有的集合或map转换为线程安全的 + */ + List list=new ArrayList(); + list.add("one"); + list.add("two"); + list=Collections.synchronizedList(list);//将现有的list集合转换为线程安全的集合 + Set set=new HashSet(list); + set=Collections.synchronizedSet(set); //转换为线程安全的set集合 + Map map=new HashMap(); + map.put("语文", 99); + map.put("数学", 95); + map.put("英语文", 58); + map=Collections.synchronizedMap(map);//转换为线程安全的map + + } + /* + * 静态方法锁: + * synchronized修饰静态方法肯定同步,因为静态方法只有一份。
+ */ + public synchronized static void dosome(){ + Thread t=Thread.currentThread(); + System.out.println(t+"正在执行dosome"); + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println(t+"执行dosome完毕"); + + } +} +class Shop{ + public void buy(){ + Thread t=Thread.currentThread(); + try { + System.out.println(t+"买"); + Thread.sleep(5000); + /* + * 同步代码块: + * 同步块需要指定同步监视器(上锁对象) + * 若希望该同步块有效,必须保证多个线程看到的锁对象相同 + * 通常使用this即可 + */ + synchronized (this) { + System.out.println(t+"试"); + Thread.sleep(5000); + } + System.out.println(t+"over"); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } +} +class Foo{ + /* + * 互斥锁 + * synchronized修饰的是两段代码,但是锁对象相同 + * 那么这两端代码就是互斥的 + */ + public synchronized void methodA(){ + Thread t=Thread.currentThread(); + System.out.println(t+"开始执行a"); + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println(t+"a结束"); + } + public synchronized void methodB(){ + Thread t=Thread.currentThread(); + System.out.println(t+"开始执行B"); + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println(t+"B结束"); + } +} diff --git a/boot-service/src/main/java/com/xwbing/demo/XmlDemo.java b/boot-service/src/main/java/com/xwbing/demo/XmlDemo.java new file mode 100644 index 0000000..d8264b6 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/demo/XmlDemo.java @@ -0,0 +1,97 @@ +package com.xwbing.demo; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.util.List; +import org.dom4j.Attribute; +import org.dom4j.Document; +import org.dom4j.DocumentHelper; +import org.dom4j.Element; +import org.dom4j.io.OutputFormat; +import org.dom4j.io.SAXReader; +import org.dom4j.io.XMLWriter; + +/** + * 创建日期: 2017年2月16日 下午1:23:16 + * 作者: xiangwb + */ + +public class XmlDemo { + + /** + * + * 功能描述:将doc对象(xml)写到文件中
+ * 作 者:xwb
+ * 创建时间:2017年2月16日 下午2:59:26
+ * + * @param doc + * @param xml + * @throws Exception + */ + private static void write2xml(Document doc, String fos) throws Exception { + FileOutputStream out = new FileOutputStream(fos); + // dom4j 提供类格式工具,可以输出时候对doc进行化妆,搞漂亮一些 + OutputFormat fmt = OutputFormat.createPrettyPrint(); + XMLWriter writer = new XMLWriter(out, fmt);// 格式 + writer.write(doc); + writer.close(); + } + + /** + * + * 功能描述: 读取XML文件到doc对象
+ * 作 者:xwb
+ * 创建时间:2017年2月16日 下午3:01:33
+ * + * @return + * @throws Exception + */ + private static Document readXml(String fis) throws Exception { + SAXReader reader = new SAXReader(); + FileInputStream in = new FileInputStream(fis); + Document doc = reader.read(in); + return doc; + } + + public static void main(String[] args) throws Exception { + Document doc = readXml("xmlDemo.xml"); + System.out.println(doc.asXML() + "..............."); + + // doc 是全部的XML文件的内容 + // doc 引用的是内存中的对象。 + Element root = doc.getRootElement();// 获取xml的根元素,访问xml中数据的唯一入口 + // 获取根元素下所有子元素,并遍历 + List list = root.elements(); + for (Element e2 : list) { + System.out.println(e2.getName());// 获取元素名字 + System.out.println(e2.getText());// 获取元素内文本内容 + } + + Element book = root.element("book");// 获取满足第一个条件的子元素 + Element name = book.element("name"); + name.setText("轶名名");// 修改元素内容 + Attribute id = book.attribute("id");// 获取属性 + System.out.println(id.getValue()); + id.setValue("b3");// 修改属性 + + // 如果修改了doc 就能实现修改xml并写文件 + // 为根元素添加子元素 + Element newOne = root.addElement("book8"); + newOne.addElement("name").setText("18岁给我一姑娘"); + newOne.addAttribute("id", "b5"); + newOne.addAttribute("lang", "中文"); + + // 找到元素并且删除这个子元素 + Element book1 = root.element("book8"); + root.remove(book1); + write2xml(doc, "demo.xml"); + + // 创建新的xml document对象 + Document newDoc = DocumentHelper.createDocument(); + // 为doc添加根元素 + Element newRoot = newDoc.addElement("students"); + newRoot.addElement("stu1"); + newRoot.addElement("stu2"); + write2xml(newDoc, "xmlDemoStu.xml"); + } +} diff --git a/boot-service/src/main/java/com/xwbing/domain/entity/vo/SysAuthVo.java b/boot-service/src/main/java/com/xwbing/domain/entity/vo/SysAuthVo.java index 4c99110..37cfc72 100644 --- a/boot-service/src/main/java/com/xwbing/domain/entity/vo/SysAuthVo.java +++ b/boot-service/src/main/java/com/xwbing/domain/entity/vo/SysAuthVo.java @@ -26,6 +26,5 @@ public class SysAuthVo extends SysAuthority { e.printStackTrace(); } } - private List children; }