diff --git a/README.en.md b/README.en.md index 59b4c09d76a1dc104b2f824ef631e22589f73d8d..deee9d3d76a1b0d59ada4f34a54ccc1afe9e8fe2 100644 --- a/README.en.md +++ b/README.en.md @@ -1,16 +1,19 @@ # Utils #### Description -想做点工具玩玩 +Many Utils For Work #### Software Architecture Software architecture description +1. maven +2. java SE + #### Installation 1. xxxx -2. xxxx -3. xxxx +2. [URL](https://gitee.com/linqiankun/Utils.git) +2. [wiki](https://gitee.com/linqiankun/Utils/wikis/Home) #### Instructions diff --git a/README.md b/README.md index b0fe798f6cc944e0eb3b385a0718737f01e2fc9b..c728f6a777ea0ac2c0b04bb7ab246a75434301ed 100644 --- a/README.md +++ b/README.md @@ -6,18 +6,24 @@ #### 软件架构 软件架构说明 +1. maven +2. java SE #### 安装教程 -1. xxxx -2. xxxx -3. xxxx +1. 直接拷贝工具类代码嵌入自己项目即可 +2. [克隆地址](https://gitee.com/linqiankun/Utils.git) +3. [文档介绍](https://gitee.com/linqiankun/Utils/wikis/Home) #### 使用说明 -1. xxxx -2. xxxx -3. xxxx +1. 直接拷贝工具类代码嵌入自己项目即可 +2. 目前已完成一部分,经测试可以使用 + - excel读取导出工具 + - 文件读取写入工具 + - Http连接工具(两个) + - xml解析工具 + - 对象反射工具 #### 参与贡献 diff --git a/pom.xml b/pom.xml index 98f0b2ef024d49a8e29e69468eab6ae5985231bc..bce3364713cf18ad6898c3953ccb4339bee7fc23 100644 --- a/pom.xml +++ b/pom.xml @@ -33,11 +33,6 @@ lombok 1.16.8 - - org.apache.poi - poi-ooxml - 3.14 - javax.servlet servlet-api @@ -60,6 +55,23 @@ slf4j-api 1.6.4 + + + com.itextpdf + itextpdf + 5.5.10 + + + com.itextpdf + itext-asian + 5.2.0 + + + + org.apache.poi + poi-ooxml + 3.14 + diff --git a/src/main/java/com/lin/App.java b/src/main/java/com/lin/App.java index f88259dff0e999b3a3ec498c59b3adb4bf052f4f..1133952050327f6237c770ee4b996fac7e8f0222 100644 --- a/src/main/java/com/lin/App.java +++ b/src/main/java/com/lin/App.java @@ -1,10 +1,21 @@ package com.lin; +import java.util.HashMap; +import java.util.Map; + /** - * Hello world! + * Hello Utils! */ public class App { public static void main(String[] args) { - System.out.println("Hello World!"); + + System.out.println("Hello Utils"); + Map m = new HashMap<>(); + m.put("ss", "ghjk"); + m.put("ss", 23456); + + Object s = m.get("s"); + + } } diff --git a/src/main/java/com/lin/Dto/BookDto.java b/src/main/java/com/lin/Dto/BookDto.java new file mode 100644 index 0000000000000000000000000000000000000000..a7fbe9fc6fdac61a9940a67a0e4025bca1ad57ad --- /dev/null +++ b/src/main/java/com/lin/Dto/BookDto.java @@ -0,0 +1,12 @@ +package com.lin.Dto; + +import lombok.Data; + +@Data +public class BookDto { + String name; + String author; + int price; + String year; + String language; +} diff --git a/src/main/java/com/lin/Dto/TestDto.java b/src/main/java/com/lin/Dto/TestDto.java new file mode 100644 index 0000000000000000000000000000000000000000..9daad1a6bb9cd408b8b0e016d3f59316ce9ccfd0 --- /dev/null +++ b/src/main/java/com/lin/Dto/TestDto.java @@ -0,0 +1,18 @@ +package com.lin.Dto; + +public class TestDto { + + + int a; + byte b; + short c; + long d; + boolean e; + float f; + double g; + char h; + String i; + Integer j; + Byte k; + +} diff --git a/src/main/java/com/lin/Util/ExportExcelUtil.java b/src/main/java/com/lin/Util/ExcelExportUtil.java similarity index 86% rename from src/main/java/com/lin/Util/ExportExcelUtil.java rename to src/main/java/com/lin/Util/ExcelExportUtil.java index 1be763ac1339c8eb5b31d08c01f02cef892543b9..9a2957af339d0d718235a8c03dfc08cfa47daaf3 100644 --- a/src/main/java/com/lin/Util/ExportExcelUtil.java +++ b/src/main/java/com/lin/Util/ExcelExportUtil.java @@ -9,18 +9,22 @@ import org.jetbrains.annotations.NotNull; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; -import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; +/** + * excel导出工具 + * + * @author 九分石人,2019-12-31 + */ @Slf4j -public class ExportExcelUtil { +public class ExcelExportUtil { /** - * 导出Excel主方法,调用此方法即可 + * 导出Excel主方法,调用此方法即可(该方法未测试) * * @param fileName 文件名 * @param list 数据源 @@ -37,10 +41,10 @@ public class ExportExcelUtil { List listError = new ArrayList<>(); listError.add("数据量超过5000,无法导出"); String[] titleError = new String[]{"数据量超过5000,无法导出"}; - excel = ExportExcelUtil.getExcel(list, titleError); + excel = ExcelExportUtil.getExcel(list, titleError); } else { // 制作导出文件 - excel = ExportExcelUtil.getExcel(list, title); + excel = ExcelExportUtil.getExcel(list, title); } fileName = new String((fileName + ".xls").getBytes(), StandardCharsets.ISO_8859_1); @@ -55,11 +59,7 @@ public class ExportExcelUtil { excel.write(os); os.flush(); os.close(); - } catch (UnsupportedEncodingException e) { - log.error(e.getMessage()); - } catch (IOException e) { - log.error(e.getMessage()); - } catch (IllegalAccessException e) { + } catch (IOException | IllegalAccessException e) { log.error(e.getMessage()); } } @@ -75,7 +75,7 @@ public class ExportExcelUtil { * @author com.lin, 2019-12-20 */ @NotNull - private static HSSFWorkbook getExcel(List list, @NotNull String[] title) throws IllegalAccessException { + public static HSSFWorkbook getExcel(List list, @NotNull String[] title) throws IllegalAccessException { // 创建一个excel文件 HSSFWorkbook wb = new HSSFWorkbook(); @@ -121,7 +121,7 @@ public class ExportExcelUtil { row.setHeightInPoints(15); // 通过反射获取对象的值并设置进excel Class c = t.getClass(); - Field[] fields = c.getFields(); + Field[] fields = c.getDeclaredFields(); for (int j = 0; j < fields.length; j++) { Field f = fields[j]; f.setAccessible(true); diff --git a/src/main/java/com/lin/Util/ImportExcelUtil.java b/src/main/java/com/lin/Util/ExcelImportUtil.java similarity index 73% rename from src/main/java/com/lin/Util/ImportExcelUtil.java rename to src/main/java/com/lin/Util/ExcelImportUtil.java index d87d237db56c32e38626e1c1ba300e25807fabe2..f423a8dff4449ad619eb1b1317fd2f0dac545a9a 100644 --- a/src/main/java/com/lin/Util/ImportExcelUtil.java +++ b/src/main/java/com/lin/Util/ExcelImportUtil.java @@ -22,23 +22,29 @@ import java.io.PushbackInputStream; import java.util.ArrayList; import java.util.List; +/** + * excel导入工具 + * + * @author 九分石人, 2019-12-31 + */ @Slf4j -public class ImportExcelUtil { +public class ExcelImportUtil { /** * 导入Excel * * @param fileInputStream 文件输入流 - * @param validColum 关键列 + * @param validColumn 关键列 + * @param startRow 开始行,如第一行就是1 * @return 数组的集合 * @author com.lin, 2019-12-19 */ @Nullable - public static List readExcelFile(InputStream fileInputStream, int validColum) { + public static List readExcelFile(InputStream fileInputStream, int validColumn, int startRow) { try { Workbook workbook = getWeebWork(fileInputStream); Sheet sheet = workbook.getSheetAt(0);// 只取sheet1的数据 - return readFromSheet(sheet, validColum); + return readFromSheet(sheet, validColumn, startRow); } catch (Exception e) { log.error(e.getMessage()); } finally { @@ -57,7 +63,7 @@ public class ImportExcelUtil { /** * 获取Workbook格式的Excel文件 * - * @param fileStream 文件输入流 + * @param inputStream 文件输入流 * @return Excel文件 * @throws IOException 文件输入流异常 * @throws InvalidFormatException 格式校验异常 @@ -65,15 +71,15 @@ public class ImportExcelUtil { */ @NotNull @Contract("_ -> new") - private static Workbook getWeebWork(@NotNull InputStream fileStream) throws IOException, InvalidFormatException { - if (!fileStream.markSupported()) { - fileStream = new PushbackInputStream(fileStream, 8); + private static Workbook getWeebWork(@NotNull InputStream inputStream) throws IOException, InvalidFormatException { + if (!inputStream.markSupported()) { + inputStream = new PushbackInputStream(inputStream, 8); } - if (POIFSFileSystem.hasPOIFSHeader(fileStream)) { - return new HSSFWorkbook(fileStream); + if (POIFSFileSystem.hasPOIFSHeader(inputStream)) { + return new HSSFWorkbook(inputStream); } - if (POIXMLDocument.hasOOXMLHeader(fileStream)) { - return new XSSFWorkbook(OPCPackage.open(fileStream)); + if (POIXMLDocument.hasOOXMLHeader(inputStream)) { + return new XSSFWorkbook(OPCPackage.open(inputStream)); } throw new IllegalArgumentException("你的excel版本目前poi解析不了"); } @@ -82,13 +88,14 @@ public class ImportExcelUtil { /** * 获取Excel文件中的数据 * - * @param sheet Excel文件中不同的Sheet - * @param validColum 关键列,不可为空 + * @param sheet Excel文件中不同的Sheet + * @param validColumn 关键列,不可为空 + * @param startRow 开始行,如第一行就是1 * @return 每一列为一个数组,所有元素为数组的集合 * @author com.lin, 2019-12-19 */ @NotNull - private static List readFromSheet(@NotNull Sheet sheet, int validColum) { + private static List readFromSheet(@NotNull Sheet sheet, int validColumn, int startRow) { List list = new ArrayList<>(); int rownum = sheet.getLastRowNum();// 获取总行 int totalCellNum = sheet.getRow(1).getLastCellNum();// 获取总列数 @@ -96,17 +103,17 @@ public class ImportExcelUtil { if (rownum >= 5000) rownum = 5000; // 从第三行开始处理数据 - for (int i = 2; i <= rownum; i++) { + for (int i = (startRow - 1); i <= rownum; i++) { Row row = sheet.getRow(i); if (row != null) { // 第X列数据不完整的话 视为无效数据 不予添加进list中 - if (row.getCell(validColum) == null) { + if (row.getCell(validColumn) == null) { continue; } try { - row.getCell(validColum).setCellType(Cell.CELL_TYPE_STRING); //设置成文本格式 + row.getCell(validColumn).setCellType(Cell.CELL_TYPE_STRING); //设置成文本格式 } catch (Exception e) { - + log.error(e.getMessage()); } String[] cells = new String[totalCellNum];// 根据标题行生成相同列数的String数组 for (int j = 0; j < totalCellNum; j++) { diff --git a/src/main/java/com/lin/Util/FileUtil.java b/src/main/java/com/lin/Util/FileReadUtil.java similarity index 70% rename from src/main/java/com/lin/Util/FileUtil.java rename to src/main/java/com/lin/Util/FileReadUtil.java index 29b9779026520ef6e62e93c7c9d2a52c28a11b28..ba5c2372a4158479dc7bc65253de54d75f9fa36b 100644 --- a/src/main/java/com/lin/Util/FileUtil.java +++ b/src/main/java/com/lin/Util/FileReadUtil.java @@ -5,8 +5,28 @@ import org.jetbrains.annotations.NotNull; import java.io.*; +/** + * 文件读取工具 + * + * @author 九分石人,2019-12-31 + */ @Slf4j -public class FileUtil { +public class FileReadUtil { + + /** + * 通过文件获取File对象 + * + * @param filePath 文件路径 + * @return 文件内容 + * @author com.lin, 2019-02-18 + */ + public static File readToFile(String filePath) { + File file = new File(filePath); + if(file.exists()){ + return file; + } + return null; + } /** @@ -35,9 +55,9 @@ public class FileUtil { log.error(e.getMessage()); } finally { try { - if (is != null) - reader.close(); if (reader != null) + reader.close(); + if (is != null) is.close(); } catch (IOException e) { log.error(e.getMessage()); @@ -46,16 +66,16 @@ public class FileUtil { } /** - * 读取文本文件内容 + * 读取文本文件内容到字符串 * * @param filePath 文件所在路径 * @return 文本内容 - * @author com.lin, 2019-13-19 + * @author com.lin, 2019-12-19 */ @NotNull - public static String readFile(String filePath) { + public static String readFileToString(String filePath) { StringBuffer sb = new StringBuffer(); - FileUtil.readToBuffer(sb, filePath); + FileReadUtil.readToBuffer(sb, filePath); return sb.toString(); } diff --git a/src/main/java/com/lin/Util/FileWriteUtil.java b/src/main/java/com/lin/Util/FileWriteUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..b3cbe26f63e5333e16a82accbe5bff524a8c93d2 --- /dev/null +++ b/src/main/java/com/lin/Util/FileWriteUtil.java @@ -0,0 +1,96 @@ +package com.lin.Util; + +import lombok.extern.slf4j.Slf4j; + +import java.io.*; + +/** + * 文件写入工具 + * + * @author 九分石人, 2020-02-19 + */ +@Slf4j +public class FileWriteUtil { + + + /** + * 判断文件是否存在,不存在则创建文件 + * + * @param filePath 文件路径 + * @return 文件对象 + * @author com.lin, 2020-02-20 + */ + public static File canCreatFile(String filePath) { + File file = new File(filePath); + try { + if (!file.exists()) { + file.createNewFile(); + } + } catch (IOException e) { + log.error(e.getMessage()); + } + return file; + } + + + /** + * 将字符串内容写出到具体文件 + * + * @param string 要写出的文件内容 + * @param filePath 要写出的文件路径 + * @author com.lin, 2020-02-19 + */ + public static void writeFromString(String string, String filePath) { + File file = FileWriteUtil.canCreatFile(filePath); + FileOutputStream outputStream = null; + BufferedWriter writer = null; + try { + outputStream = new FileOutputStream(file); + writer = new BufferedWriter(new OutputStreamWriter(outputStream)); + writer.write(string); + } catch (IOException e) { + log.error(e.getMessage()); + } finally { + try { + if (writer != null) + writer.close(); + if (outputStream != null) + outputStream.close(); + } catch (IOException e) { + log.error(e.getMessage()); + } + } + } + + /** + * 将输入流内容写出到具体文件 + * + * @param inputStream 要写出的输入流 + * @param filePath 要写出的文件路径 + * @author com.lin, 2020-02-20 + */ + public static void writeFromInputStream(InputStream inputStream, String filePath) { + File file = FileWriteUtil.canCreatFile(filePath); + FileOutputStream outputStream = null; + try { + byte[] b = new byte[1024]; + outputStream = new FileOutputStream(file); + while (inputStream.read(b) > 0) { + outputStream.write(b); + } + } catch (FileNotFoundException e) { + log.error(e.getMessage()); + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (outputStream != null) + outputStream.close(); + } catch (IOException e) { + log.error(e.getMessage()); + } + } + + } + +} diff --git a/src/main/java/com/lin/Util/HttpConnectionUtil.java b/src/main/java/com/lin/Util/HttpConnectionUtil.java index 9b77804964f89548ea6e9aceae9c93f77e150512..ee82de7c00f8ca344657f63eb40b7a50cc463f04 100644 --- a/src/main/java/com/lin/Util/HttpConnectionUtil.java +++ b/src/main/java/com/lin/Util/HttpConnectionUtil.java @@ -7,6 +7,11 @@ import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; +/** + * Http连接工具 + * + * @author 九分石人, 2019-12-31 + */ @Slf4j public class HttpConnectionUtil { @@ -20,11 +25,10 @@ public class HttpConnectionUtil { * * @param url url地址 * @return 返回的信息 - * @author com.lin, 2019-13-20 + * @author com.lin, 2019-12-20 */ public static String sendGet(String url) { HttpURLConnection connection = null; - PrintWriter outPrintWriter = null; InputStream inputStream = null; String result = ""; try { @@ -50,7 +54,7 @@ public class HttpConnectionUtil { } catch (Exception e) { log.error(e.getMessage()); } finally { - closeConnection(connection, outPrintWriter, inputStream); + closeConnection(connection, null, inputStream); } return result; } @@ -61,7 +65,7 @@ public class HttpConnectionUtil { * @param url url地址 * @param body 发送的信息 * @return 返回的信息 - * @author com.lin, 2019-13-20 + * @author com.lin, 2019-12-20 */ public static String sendPost(String url, String body) { HttpURLConnection connection = null; @@ -106,7 +110,7 @@ public class HttpConnectionUtil { * @param conn url连接 * @param out 输出流 * @param in 输入流 - * @author com.lin, 2019-13-20 + * @author com.lin, 2019-12-20 */ private static void closeConnection(HttpURLConnection conn, Writer out, InputStream in) { try { @@ -130,7 +134,7 @@ public class HttpConnectionUtil { * @param inputStream 输入流 * @param encode 编码 * @return 从输入流获取的字符串 - * @author com.lin, 2019-13-20 + * @author com.lin, 2019-12-20 */ private static String changeInputStream(InputStream inputStream, String encode) { @@ -159,7 +163,7 @@ public class HttpConnectionUtil { * @param url 原url 包含 * @return newURL 新的Url * @throws UnsupportedEncodingException 编码异常 - * @author com.lin, 2019-13-19 + * @author com.lin, 2019-12-19 */ private static String getNewUrlByUrlEncodeParam(String url) throws UnsupportedEncodingException { StringBuilder urlForEncode = new StringBuilder(); diff --git a/src/main/java/com/lin/Util/HttpUrlConnectionUtil.java b/src/main/java/com/lin/Util/HttpUrlConnectionUtil.java index e8505def4d33e36bbde538bec1a5980593e4da4a..b9406d956e7df23cb69d7b9fddac131aba4d1b67 100644 --- a/src/main/java/com/lin/Util/HttpUrlConnectionUtil.java +++ b/src/main/java/com/lin/Util/HttpUrlConnectionUtil.java @@ -3,7 +3,9 @@ package com.lin.Util; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; -import javax.net.ssl.*; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; import java.io.DataOutputStream; import java.net.HttpURLConnection; import java.net.URL; @@ -12,7 +14,9 @@ import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; /** - * @author com.lin, 2019-13-21 + * Http连接工具 + * + * @author com.lin, 2019-12-21 */ @Slf4j public class HttpUrlConnectionUtil { @@ -25,6 +29,7 @@ public class HttpUrlConnectionUtil { * * @param urlStr url地址 * @return 返回的信息 + * @author com.lin, 2019-12-21 */ public static String doGet(String urlStr) { URL url; @@ -32,7 +37,7 @@ public class HttpUrlConnectionUtil { try { url = new URL(urlStr); connection = (HttpURLConnection) url.openConnection(); - SSLSocketFactory ssl = HttpUrlConnectionUtil.getSSL(); +// SSLSocketFactory ssl = HttpUrlConnectionUtil.getSSL(); // https请求需要 // connection.setSSLSocketFactory(ssl); connection.setDoOutput(true); @@ -68,6 +73,7 @@ public class HttpUrlConnectionUtil { * @param urlStr url地址 * @param content 发送的信息 * @return 返回的信息 + * @author com.lin, 2019-12-21 */ public static String doPost(String urlStr, String content) { URL url; @@ -75,7 +81,7 @@ public class HttpUrlConnectionUtil { try { url = new URL(urlStr); connection = (HttpURLConnection) url.openConnection(); - SSLSocketFactory ssl = HttpUrlConnectionUtil.getSSL(); +// SSLSocketFactory ssl = HttpUrlConnectionUtil.getSSL(); // https请求需要 // connection.setSSLSocketFactory(ssl); connection.setDoOutput(true); @@ -115,8 +121,9 @@ public class HttpUrlConnectionUtil { * @throws NoSuchProviderException 异常 * @throws NoSuchAlgorithmException 异常 * @throws KeyManagementException 异常 + * @author com.lin, 2019-12-21 */ - private static SSLSocketFactory getSSL() throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException { + private static SSLSocketFactory getSSL() throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException { TrustManager[] trustManager = new TrustManager[]{}; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, trustManager, new java.security.SecureRandom()); diff --git a/src/main/java/com/lin/Util/InvokeUtil.java b/src/main/java/com/lin/Util/InvokeUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..fd309e8361f44ff3c98b0a5aa559c35d58b99f76 --- /dev/null +++ b/src/main/java/com/lin/Util/InvokeUtil.java @@ -0,0 +1,111 @@ +package com.lin.Util; + +import com.sun.org.apache.xpath.internal.operations.Bool; +import lombok.extern.slf4j.Slf4j; + +import javax.swing.*; +import java.lang.reflect.Field; +import java.lang.reflect.Type; +import java.util.Map; + +/** + * 反射的工具类 + * + * @author 九分石人, 2020-02-21 + */ +@Slf4j +public class InvokeUtil { + + /** + * 将Map中的数据反射到对象中 + * + * @param 要反射的对象类型 + * @param t 反射的对象 + * @param map 属性值的集合 + * @author com.lin, 2020-02-21 + */ + public static void setFromMap(T t, Map map) { + Class c = t.getClass(); + Field[] fields = c.getDeclaredFields(); + try { + for (Field f : fields) { + setFormatValue(t, map, f); + } + } catch (IllegalAccessException e) { + log.error(e.getMessage()); + } + + } + + /** + * 将不同格式的数据按字段反射进对象中 + * + * @param t 反射的类对象 + * @param map 对象值的集合 + * @param f 字段的名称 + * @param 反射对象的类型 + * @throws IllegalAccessException 参数非法异常 + * @author com.lin, 2020-02-22 + */ + private static void setFormatValue(T t, Map map, Field f) throws IllegalAccessException { + f.setAccessible(true); + String key = f.toString().substring(f.toString().lastIndexOf(".") + 1); + String typeName = f.getGenericType().getTypeName(); + switch (typeName) { + case "boolean": + f.setBoolean(t, Boolean.parseBoolean(map.get(key))); + break; + case "java.lang.Boolean": + f.set(t, Boolean.parseBoolean(map.get(key))); + break; + case "byte": + f.setByte(t, Byte.parseByte(map.get(key))); + break; + case "java.lang.Byte": + f.set(t, Byte.parseByte(map.get(key))); + break; + case "char": + f.setChar(t, map.get(key).charAt(0)); + break; + case "java.lang.Character": + f.set(t, map.get(key).charAt(0)); + break; + case "double": + f.setDouble(t, Double.parseDouble(map.get(key))); + break; + case "java.lang.Double": + f.set(t, Double.parseDouble(map.get(key))); + break; + case "float": + f.setFloat(t, Float.parseFloat(map.get(key))); + break; + case "java.lang.Float": + f.set(t, Float.parseFloat(map.get(key))); + break; + case "int": + f.setInt(t, Integer.parseInt(map.get(key))); + break; + case "java.lang.Integer": + f.set(t, Integer.parseInt(map.get(key))); + break; + case "long": + f.setLong(t, Long.parseLong(map.get(key))); + break; + case "java.lang.Long": + f.set(t, Long.parseLong(map.get(key))); + break; + case "short": + f.setShort(t, Short.parseShort(map.get(key))); + break; + case "java.lang.Short": + f.set(t, Short.parseShort(map.get(key))); + break; + case "java.lang.String": + f.set(t, map.get(key)); + break; + default: + break; + } + } + +} diff --git a/src/main/java/com/lin/Util/XmlParseUtil.java b/src/main/java/com/lin/Util/XmlParseUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..0456574272be25048d885e71a36033e1ff2334fc --- /dev/null +++ b/src/main/java/com/lin/Util/XmlParseUtil.java @@ -0,0 +1,126 @@ +package com.lin.Util; + +import lombok.extern.slf4j.Slf4j; +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * Xml文件读取工具 + * + * @author 九分石人, 2020-02-17 + */ +@Slf4j +public class XmlParseUtil { + + /** + * 根据节点获取节点的属性值 + * + * @param node 要获取属性值的节点 + * @return 节点的属性值 + * @author com.lin, 2020-02-20 + */ + public static Map getAttrByNode(Node node) { + Map attrMap = new HashMap<>(); + NamedNodeMap attributes = node.getAttributes(); + for (int j = 0; j < attributes.getLength(); j++) { + Node attr = attributes.item(j); + String nodeName = attr.getNodeName(); + String nodeValue = attr.getNodeValue(); + attrMap.put(nodeName, nodeValue); + } + return attrMap; + } + + /** + * 获取节点的子节点名和子节点值 + * + * @param node 要获取子节点名和值的节点 + * @return 子节点的名和值 + * @author com.lin, 2020-02-20 + */ + public static Map getChildNodeValueByNode(Node node) { + Map nodeMap = new HashMap<>(); + NodeList childNodes = node.getChildNodes(); + for (int j = 0; j < childNodes.getLength(); j++) { + //排除掉换行造成的无效节点 + if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE) { + String nodeName = childNodes.item(j).getNodeName(); + String nodeValue = childNodes.item(j).getFirstChild().getNodeValue(); + nodeMap.put(nodeName, nodeValue); + } + } + return nodeMap; + } + + + /** * 读取Xml文件,后续根据此方法进行修改,进行二次开发 + + * + * @param filepath Xml文件的路径 + * @param node Xml文件中根结点的名称 + * @author com.lin, 2020-02-19 + */ + public static void ReadXml(String filepath, String node) { + + NodeList elementsByTagName = getNodeList(filepath, node); + assert elementsByTagName != null; + for (int i = 0; i < elementsByTagName.getLength(); i++) { + Node item = elementsByTagName.item(i); + //获取节点的所有属性 + Map attrMap = XmlParseUtil.getAttrByNode(item); + //获取节点所有子节点值 + Map childNodeValueByNode = XmlParseUtil.getChildNodeValueByNode(item); + } + } + + /** + * 读取Xml文件,获取根结点集合 + * + * @param filepath Xml文件的路径X + * @param node Xml文件中根结点的名称 + * @return 根结点集合 + * @author com.lin, 2020-02-21 + */ + public static NodeList getNodeList(String filepath, String node) { + Document document; + try { + document = getDocument(filepath); + //根据标签名获取所有根结点的集合 + return document.getElementsByTagName(node); + } catch (ParserConfigurationException | SAXException | IOException e) { + log.error(e.getMessage()); + } + return null; + + } + + /** + * 根据Xml获取Document对象 + * + * @return Document对象 + * @throws ParserConfigurationException Xml异常 + * @throws SAXException 解析异常 + * @throws IOException 文件读取异常 + * @author com.lin, 2020-02-20 + */ + private static Document getDocument(String filepath) throws ParserConfigurationException, SAXException, IOException { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = dbf.newDocumentBuilder(); + File file = FileReadUtil.readToFile(filepath); + assert file != null; + return documentBuilder.parse(file); + } + + +} diff --git a/src/main/resources/book.xml b/src/main/resources/book.xml new file mode 100644 index 0000000000000000000000000000000000000000..22b2785e74861d3ae55bdbe76f73ebfc33156e2f --- /dev/null +++ b/src/main/resources/book.xml @@ -0,0 +1,15 @@ + + + + 冰与火之歌 + 乔治马丁 + 2014 + 89 + + + 安徒生童话 + 2004 + 98 + English + + \ No newline at end of file diff --git a/src/test/java/com/lin/AppTest.java b/src/test/java/com/lin/AppTest.java index dbadd8e70baa7ffc6cfbb01c2e15787b0e284757..dd879cf57fdf2ddd41b968790fe7c00fbcfa4492 100644 --- a/src/test/java/com/lin/AppTest.java +++ b/src/test/java/com/lin/AppTest.java @@ -1,7 +1,5 @@ package com.lin; -import static org.junit.Assert.assertTrue; - import org.junit.Test; /** @@ -13,6 +11,18 @@ public class AppTest { */ @Test public void shouldAnswerWithTrue() { - assertTrue(true); + + char b = 'b'; + for (int i = 0; i < 10; i++) { + switch (b) { + case 'a': + break; + case 'b': + continue; + default: + break; + } + System.out.println(i); + } } } diff --git a/src/test/java/com/lin/TestUtil/ExcelTest.java b/src/test/java/com/lin/TestUtil/ExcelTest.java new file mode 100644 index 0000000000000000000000000000000000000000..316469f66701b02075f3af87032c82b927dd184b --- /dev/null +++ b/src/test/java/com/lin/TestUtil/ExcelTest.java @@ -0,0 +1,54 @@ +package com.lin.TestUtil; + +import com.lin.Dto.BookDto; +import com.lin.Util.ExcelExportUtil; +import com.lin.Util.ExcelImportUtil; +import com.lin.Util.FileWriteUtil; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.junit.Test; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; + +/** + * excel测试 + */ +public class ExcelTest { + + + @Test + public void exportExcelTest() throws IllegalAccessException, IOException { +// String filepath = "/Users/linqiankun/Desktop/testexcel.xls"; + String filepath = "src/test/resources/testExcel.xml"; + BookDto b = new BookDto(); + b.setAuthor("cvbnm"); + b.setLanguage("english"); + b.setName("ihii"); + b.setPrice(90); + b.setYear("2020"); + List l = new ArrayList<>(); + l.add(b); + String[] str = {"name", "author", "price", "language", "year"}; + + HSSFWorkbook excel = ExcelExportUtil.getExcel(l, str); + + File file = FileWriteUtil.canCreatFile(filepath); + FileOutputStream out = new FileOutputStream(file); + excel.write(out); + + } + + @Test + public void importExcelTest() throws FileNotFoundException { +// String filepath = "/Users/linqiankun/Desktop/testexcel.xls"; + String filepath = "src/test/resources/testExcel.xml"; + File file = FileWriteUtil.canCreatFile(filepath); + FileInputStream in = new FileInputStream(file); + List strings = ExcelImportUtil.readExcelFile(in, 1, 2);//从第二行开始读,就是2 + System.out.println(strings); + + } + + +} diff --git a/src/test/java/com/lin/TestUtil/ExportExcelTest.java b/src/test/java/com/lin/TestUtil/ExportExcelTest.java deleted file mode 100644 index 17e63f7edfa5d3f1d1a9c1fff6e09b6773bdad35..0000000000000000000000000000000000000000 --- a/src/test/java/com/lin/TestUtil/ExportExcelTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.lin.TestUtil; - -import org.junit.Test; - -public class ExportExcelTest { - - - @Test - public void export(){ - - - } - - -} diff --git a/src/test/java/com/lin/TestUtil/FileTest.java b/src/test/java/com/lin/TestUtil/FileTest.java index 9899b6225dfbbc781f17a3d7c81e341f0653477d..505ace7943b2ba6da2ba4f1faebb6fa13da09952 100644 --- a/src/test/java/com/lin/TestUtil/FileTest.java +++ b/src/test/java/com/lin/TestUtil/FileTest.java @@ -2,24 +2,43 @@ package com.lin.TestUtil; import com.alibaba.fastjson.JSON; import com.lin.Dto.SenseCallbackDto; -import com.lin.Util.FileUtil; +import com.lin.Util.FileReadUtil; +import com.lin.Util.FileWriteUtil; import org.junit.Test; import java.io.IOException; +import java.io.InputStream; import java.util.List; +/** + * 文件读取测试,将读取到的文件反射进对象集合中 + */ public class FileTest { - - @Test - public void fileTest() throws IOException { + public void readFileToStringTest() throws IOException { +// String filepath = "/Users/linqiankun/Desktop/test"; + String filepath = "src/test/resources/test"; + String s = FileReadUtil.readFileToString(filepath); - String s = FileUtil.readFile("/Users/linqiankun/Desktop/test"); List reslutList = JSON.parseArray(s, SenseCallbackDto.class); System.out.println(reslutList.size()); + } + @Test + public void writeFromStringTest() { +// String filepath = "/Users/linqiankun/Desktop/test"; + String filepath = "src/test/resources/test"; + String s = "wertyukmcdrtyukmnhgfrtyu"; + FileWriteUtil.writeFromString(s, filepath); } + @Test + public void writeFromInputStreamTest() { + InputStream in = this.getClass().getClassLoader().getResourceAsStream("book.xml"); +// String filepath = "/Users/linqiankun/Desktop/test1"; + String filepath = "src/test/resources/test"; + FileWriteUtil.writeFromInputStream(in,filepath); + } -} +} \ No newline at end of file diff --git a/src/test/java/com/lin/TestUtil/HttpConnectionTest.java b/src/test/java/com/lin/TestUtil/HttpConnectionTest.java index 5d4ab5de847646fa3f999d2e5588ba5045078df9..e1eb40915da890a740003dfcf36dd6e27bccb880 100644 --- a/src/test/java/com/lin/TestUtil/HttpConnectionTest.java +++ b/src/test/java/com/lin/TestUtil/HttpConnectionTest.java @@ -4,6 +4,9 @@ import com.lin.Util.HttpConnectionUtil; import com.lin.Util.HttpUrlConnectionUtil; import org.junit.Test; +/** + * http连接测试 + */ public class HttpConnectionTest { @Test diff --git a/src/test/java/com/lin/TestUtil/InvokeTest.java b/src/test/java/com/lin/TestUtil/InvokeTest.java index 60c83ff3fb429c3e6f20aded68760754e70ec84b..56eb3f48f7f469ba85a32e691765b4a625ff9e79 100644 --- a/src/test/java/com/lin/TestUtil/InvokeTest.java +++ b/src/test/java/com/lin/TestUtil/InvokeTest.java @@ -1,12 +1,41 @@ package com.lin.TestUtil; +import com.lin.Dto.BookDto; import com.lin.Dto.SenseCallbackDto; +import com.lin.Dto.TestDto; +import com.lin.Util.InvokeUtil; +import com.lin.Util.XmlParseUtil; +import org.junit.Test; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; import java.lang.reflect.Field; -import java.util.Date; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +/** + * 反射测试 + */ public class InvokeTest { + @Test + public void setFromMapTest() { + String filepath = "src/test/resources/book.xml"; + List l = new ArrayList<>(); + NodeList book = XmlParseUtil.getNodeList(filepath, "book"); + for (int i = 0; i < book.getLength(); i++) { + Node item = book.item(i); + BookDto bookDto = new BookDto(); + //获取节点所有子节点值 + Map childNodeValueByNode = XmlParseUtil.getChildNodeValueByNode(item); + InvokeUtil.setFromMap(bookDto, childNodeValueByNode); + l.add(bookDto); + } + System.out.println(l.toString()); + + } + public static void main(String[] args) throws IllegalAccessException { SenseCallbackDto dto = new SenseCallbackDto(); @@ -26,19 +55,19 @@ public class InvokeTest { dto.setTemplateCode("ghjk,"); dto.setResultCode(1); + TestDto t = new TestDto(); - Class c = dto.getClass(); + Class c = t.getClass(); Field[] fields = c.getDeclaredFields(); for (Field f : fields) { f.setAccessible(true); + System.out.println(f.getType().getName()); + System.out.println(f.getGenericType().getTypeName()); String substring = f.toString().substring(f.toString().lastIndexOf(".") + 1); - System.out.println(f.toString()+f.get(dto)); - f.set(dto,"s"); + System.out.println(f.toString()); } - - } diff --git a/src/test/java/com/lin/TestUtil/XmlTest.java b/src/test/java/com/lin/TestUtil/XmlTest.java new file mode 100644 index 0000000000000000000000000000000000000000..e962f2246fdc4ab344e487930c9781bf58df56e4 --- /dev/null +++ b/src/test/java/com/lin/TestUtil/XmlTest.java @@ -0,0 +1,35 @@ +package com.lin.TestUtil; + +import com.lin.Util.FileReadUtil; +import com.lin.Util.XmlParseUtil; +import org.junit.Test; +import org.xml.sax.SAXException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +/** + * Xml相关测试工具 + */ +public class XmlTest { + + @Test + public void xmlParseTest() throws ParserConfigurationException, IOException, SAXException { + String filepath = "src/test/resources/book.xml"; + XmlParseUtil.ReadXml(filepath,"book"); + +// InputStream is = this.getClass().getResourceAsStream("/book.xml"); // 拿到资源 +// InputStream in = this.getClass().getClassLoader().getResourceAsStream("book.xml"); +// URL resource = this.getClass().getClassLoader().getResource("book.xml"); +// DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); +// DocumentBuilder documentBuilder = dbf.newDocumentBuilder(); +// documentBuilder.parse(FileReadUtil.readFileToString(filepath)); +// documentBuilder.parse(String.valueOf(resource)); + } + + +} diff --git a/src/test/resources/book.xml b/src/test/resources/book.xml new file mode 100644 index 0000000000000000000000000000000000000000..22b2785e74861d3ae55bdbe76f73ebfc33156e2f --- /dev/null +++ b/src/test/resources/book.xml @@ -0,0 +1,15 @@ + + + + 冰与火之歌 + 乔治马丁 + 2014 + 89 + + + 安徒生童话 + 2004 + 98 + English + + \ No newline at end of file