java冷门小功能代码收集
生活随笔
收集整理的這篇文章主要介紹了
java冷门小功能代码收集
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
- 1. 獲取本地文件的Mimetype
- 2. 獲取超大圖片的尺寸
- 3. 使用itextpdf獲取pdf文件的尺寸
- 4. 原生代碼復制文件
- 5.單例模式在單例類中加入下面的方法可以防止反序列化漏洞
- 6.解決跨域問題原生代碼
- 7.獲取當前ISODATETIME格式的時間字符串
- 8.字符串脫敏
- 9.判斷脫敏字符串是否與明文匹配
- 10.從給定的Class類獲取JAR文件的完整路徑
- 11.獲取項目里的資源輸入流
1. 獲取本地文件的Mimetype
import java.net.URLConnection;String contentType = URLConnection.getFileNameMap().getContentTypeFor(filePath);2. 獲取超大圖片的尺寸
import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.FileImageInputStream;try (FileImageInputStream inputStream = new FileImageInputStream(new File(imageFilePath));) {Iterator<ImageReader> readers = ImageIO.getImageReaders(inputStream);if (readers.hasNext()) {ImageReader reader = readers.next();reader.setInput(inputStream);int width = reader.getWidth(reader.getMinIndex(); //圖片寬度int height = reader.getHeight(reader.getMinIndex()); //圖片高度}inputStream.flush(); } catch (Exception e) {log.error("讀取圖片時異常", e); }3. 使用itextpdf獲取pdf文件的尺寸
import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfReader;PdfReader pdfReader = null; try {pdfReader = new PdfReader(pdfPath);Rectangle pageSize = pdfReader.getPageSize(1); 1表示首頁int width = pageSize.getWidth(); //寬高int height = pageSize.getHeight(); //高度 } catch (Exception e) {log.error("讀取pdf時異常", e); } finally {if (pdfReader != null) {pdfReader.close();} }4. 原生代碼復制文件
import java.io.File; import java.nio.file.Files; import java.nio.file.StandardCopyOption; //StandardCopyOption.REPLACE_EXISTING覆蓋已存在的文件 Files.copy(new File(videoFormat.getParent(), videoFormat.getName()).toPath(), new File(outFilePath).toPath(), StandardCopyOption.REPLACE_EXISTING);5.單例模式在單例類中加入下面的方法可以防止反序列化漏洞
//反序列化時,如果定義了readResolve(),則直接返回此方法指定的對象,而不再單獨創建新對象。 private Object readResolve() throws ObjectStreamException {return instance; }6.解決跨域問題原生代碼
public static void originEnable(HttpServletRequest request, HttpServletResponse response) {String origin = request.getHeader("Origin");if (origin != null && !origin.equals("")) {//帶cookie的時候,origin必須是全匹配,不能使用*response.addHeader("Access-Control-Allow-Origin", origin);}//允許提交請求的方法,*表示全部允許//GET, POST, PUT, DELETE, PATCH...response.addHeader("Access-Control-Allow-Methods", "*");//支持所有自定義頭if (headers != null && !headers.equals("")) {//Content-Type, x-requested-with, X-Custom-Header, Custom-Access-Token...response.addHeader("Access-Control-Allow-Headers", headers);}//預檢請求的緩存時間(秒),即在這個時間段里,對于相同的跨域請求不會再預檢response.addHeader("Access-Control-Max-Age", "3600"); }7.獲取當前ISODATETIME格式的時間字符串
//yyyy-MM-ddTHH:mm:ss DateTimeFormatter formatter = new DateTimeFormatterBuilder().parseCaseInsensitive().append(DateTimeFormatter.ISO_LOCAL_DATE).appendLiteral('T').appendPattern("HH:mm:ss").toFormatter();String isoDateTime = LocalDateTime.now(ZoneId.of("+8")).format(formatter);System.out.println(isoDateTime);8.字符串脫敏
/*** @param source 源字符串* @param start 脫敏開始位置(包含)允許負數,負數即為從右邊數* @param end 脫敏結束位置(不包含)允許負數,負數即為從右邊數* @return 脫敏后的字符串*/ public static String desense(String source, int start, int end) {if (source == null || "".equals(source)) {return source;}int length = source.length();if (start < 0) {start += length;}if (start < 0) {start = 0;}if (end < 0) {end += length + 1;}if (end < 0) {end = length;}if (start - length > 0) {start = length;}if (end - length > 0) {end = length;}if (start > end) {int t = start;start = end;end = t;}if (start == end) {return source;}String pre = source.substring(0, start);String suff = source.substring(end);StringBuilder stars = new StringBuilder();for (int i = 0; i < end - start; i++) {stars.append("*");}return pre + stars.toString() + suff; }9.判斷脫敏字符串是否與明文匹配
/*** 判斷脫敏字符串是否與明文匹配* @param naked 明文字符串* @param occlude 脫敏字符串, *表示0個或多個字符* @return true,匹配;false,不匹配*/public static boolean like(String naked, String occlude) {if (StringUtils.isEmpty(naked) || StringUtils.isEmpty(occlude)) {return false;}if (!occlude.contains("*")) {return naked.equals(occlude);}//occludeArr.length至少為2String[] occludeArr = occlude.split("\\*+", -1);String start = occludeArr[0];if (StringUtils.isNotEmpty(start)) {int index = naked.indexOf(start);if (index != 0) {return false;}naked = naked.substring(start.length());}String end = occludeArr[occludeArr.length - 1];if (StringUtils.isNotEmpty(end)) {int lastIndex = naked.lastIndexOf(end);if (naked.length() - lastIndex - end.length() != 0) {return false;}naked = naked.substring(0, lastIndex);}if (occludeArr.length < 3) {//無中間段,返回truereturn true;}for (int i = 1, int loop = occludeArr.length - 1; i < loop; i++) {String middle = occludeArr[i];if (StringUtils.isEmpty(middle)) {continue;}if (naked.isEmpty()) {return false;}int index = naked.indexOf(middle);if (index < 0) {return false;}naked = naked.substring(index + middle.length());}return true; }10.從給定的Class類獲取JAR文件的完整路徑
/*** 從給定的Class類獲取JAR文件的完整路徑* @param clazz 類實例* @return jar包在本機的絕對路徑*/ public static String getJarFilePath(Class<?> clazz) {try {return getProtectionDomain(clazz);} catch (Exception e) {}return getResource(clazz); }private static String getProtectionDomain(Class<?> clazz) throws URISyntaxException {URL url = clazz.getProtectionDomain().getCodeSource().getLocation();return Paths.get(url.toURI()).toString(); }private static String getResource(Class<?> clazz) {URL resource = clazz.getResource(clazz.getSimpleName() + ".class");if (resource == null) {throw new RuntimeException("class resource is null");}String url = resource.toString();System.out.println(url);if (url.startsWith("jar:file:")) {String path = url.replaceAll("^jar:(file:.*[.]jar)!/.*", "$1");try {return Paths.get(new URL(path).toURI()).toString();} catch (Exception e) {throw new RuntimeException("Invalid Jar File URL String");}}throw new RuntimeException("Invalid Jar File URL String"); }11.獲取項目里的資源輸入流
支持本地項目、war包、jar包
public class JarUtils {/*** 獲取項目里的資源輸入流* @param sourcePath 項目編譯后classes目錄下的文件路徑, 如application.properties、com/xxx/util/JarUtils.class* @return null 如果未找到文件*/public static InputStream getResourceAsStream(String sourcePath) {return JarUtils.class.getClassLoader().getResourceAsStream(sourcePath);} }總結
以上是生活随笔為你收集整理的java冷门小功能代码收集的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: yum安装Mariadb,二进制安装Ma
- 下一篇: 如何Python写一个安卓APP