Java工具類
-
IoUtil.copy工具類,實現文件的下載
導入依賴
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> </dependency>
示例代碼:
try (InputStream is = new FileInputStream(new File("E:/" + fileName + ".txt")); OutputStream os = response.getOutputStream()) { response.setContentType("application/x-download"); response.addHeader("Content-Disposition", "attachment;filename=test.txt"); // apache提供的文件下載的工具類 IOUtils.copy(is, os); os.flush(); }
-
RandomStringUtils.randomNumeric()生成指定位數的隨機數
導入依賴:
<dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> </dependency>
示例代碼:
RandomStringUtils.randomNumeric(8); // 生成8位隨機數
-
ReflectionToStringBuilder工具類,利用反射打印對象(對象沒有重寫toString方法)
導入maven依賴
<dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> </dependency>
示例代碼:
System.out.println(ReflectionToStringBuilder.toString(user, ToStringStyle.MULTI_LINE_STYLE));
-
HTML工具類,獲取HTML中的指定的所有元素
導入依賴:
<dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.11.2</version> </dependency>
示例代碼:獲取HTML中的所有圖片地址
/** * @Description: 獲取給定html中所有的圖片的src地址 */ public static List<String> getAllImgSrcs(String html) { Document doc = Jsoup.parse(html); Elements imgs = doc.select("img"); return imgs.stream() .map(img -> img.attr("src")) .collect(Collectors.toList()); }