Java常用工具类处理方法100例
Java常用工具类处理方法100例
在Java开发过程中,我们经常需要使用各种工具类来简化代码编写、提高开发效率。本文档整理了100个常用的工具类处理方法,涵盖了字符串处理、加密解密、文件操作、日期时间处理等多个方面。
目录
- 字符串处理相关(1-20)
- 加密解密相关(21-30)
- 文件操作相关(31-50)
- 日期时间处理相关(51-60)
- 集合操作相关(61-70)
- 数字计算相关(71-80)
- 网络请求相关(81-90)
- 其他常用工具(91-100)
字符串处理相关(1-20)
1. 字符串拼接
public static String concatStrings(String... strs) {StringBuilder sb = new StringBuilder();for (String str : strs) {sb.append(str);}return sb.toString();
}
用途:将多个字符串连接成一个字符串
2. 字符串反转
public static String reverseString(String str) {return new StringBuilder(str).reverse().toString();
}
用途:将字符串中的字符顺序颠倒
3. 判断字符串是否为空
public static boolean isEmpty(String str) {return str == null || str.length() == 0;
}
用途:检查字符串是否为null或空字符串
4. 判断字符串是否不为空
public static boolean isNotEmpty(String str) {return !isEmpty(str);
}
用途:检查字符串是否非null且非空字符串
5. 去除字符串两端空白字符
public static String trim(String str) {return str == null ? null : str.trim();
}
用途:去除字符串开头和结尾的空白字符
6. 字符串转大写
public static String toUpperCase(String str) {return str == null ? null : str.toUpperCase();
}
用途:将字符串中的所有字符转换为大写
7. 字符串转小写
public static String toLowerCase(String str) {return str == null ? null : str.toLowerCase();
}
用途:将字符串中的所有字符转换为小写
8. 获取字符串长度
public static int getStringLength(String str) {return str == null ? 0 : str.length();
}
用途:获取字符串的字符数
9. 截取字符串
public static String substring(String str, int start, int end) {if (str == null) {return null;}return str.substring(start, end);
}
用途:截取指定位置的字符串子串
10. 查找子字符串位置
public static int indexOf(String str, String searchStr) {if (str == null || searchStr == null) {return -1;}return str.indexOf(searchStr);
}
用途:查找子字符串在主字符串中的首次出现位置
11. 替换字符串
public static String replace(String str, String target, String replacement) {if (str == null || target == null || replacement == null) {return str;}return str.replace(target, replacement);
}
用途:替换字符串中所有匹配的目标字符串
12. 分割字符串
public static String[] split(String str, String separator) {if (str == null) {return null;}return str.split(separator);
}
用途:根据分隔符将字符串分割为字符串数组
13. 字符串左填充
public static String leftPad(String str, int size, char padChar) {if (str == null) {return null;}int pads = size - str.length();if (pads <= 0) {return str;}return repeat(padChar, pads) + str;
}
用途:在字符串左侧填充指定字符至指定长度
14. 字符串右填充
public static String rightPad(String str, int size, char padChar) {if (str == null) {return null;}int pads = size - str.length();if (pads <= 0) {return str;}return str + repeat(padChar, pads);
}
用途:在字符串右侧填充指定字符至指定长度
15. 重复字符
public static String repeat(char ch, int repeat) {char[] buf = new char[repeat];for (int i = 0; i < buf.length; i++) {buf[i] = ch;}return new String(buf);
}
用途:生成重复指定次数的字符组成的字符串
16. 首字母大写
public static String capitalize(String str) {if (str == null || str.length() == 0) {return str;}return str.substring(0, 1).toUpperCase() + str.substring(1);
}
用途:将字符串的第一个字符转换为大写
17. 首字母小写
public static String uncapitalize(String str) {if (str == null || str.length() == 0) {return str;}return str.substring(0, 1).toLowerCase() + str.substring(1);
}
用途:将字符串的第一个字符转换为小写
18. 驼峰命名转下划线
public static String camelToUnderline(String str) {if (str == null || str.isEmpty()) {return str;}StringBuilder sb = new StringBuilder();for (int i = 0; i < str.length(); i++) {char c = str.charAt(i);if (Character.isUpperCase(c)) {if (i > 0) {sb.append("_");}sb.append(Character.toLowerCase(c));} else {sb.append(c);}}return sb.toString();
}
用途:将驼峰命名法转换为下划线命名法
19. 下划线命名转驼峰
public static String underlineToCamel(String str) {if (str == null || str.isEmpty()) {return str;}StringBuilder sb = new StringBuilder();boolean upperCase = false;for (int i = 0; i < str.length(); i++) {char c = str.charAt(i);if (c == '_') {upperCase = true;} else if (upperCase) {sb.append(Character.toUpperCase(c));upperCase = false;} else {sb.append(c);}}return sb.toString();
}
用途:将下划线命名法转换为驼峰命名法
20. 字符串是否包含子串
public static boolean contains(String str, String searchStr) {if (str == null || searchStr == null) {return false;}return str.contains(searchStr);
}
用途:判断字符串是否包含指定的子字符串
加密解密相关(21-30)
21. MD5加密
public static String md5(String str) {try {MessageDigest md = MessageDigest.getInstance("MD5");byte[] bytes = md.digest(str.getBytes("UTF-8"));return toHex(bytes);} catch (Exception e) {throw new RuntimeException(e);}
}private static String toHex(byte[] bytes) {StringBuilder sb = new StringBuilder();for (byte b : bytes) {sb.append(String.format("%02x", b));}return sb.toString();
}
用途:对字符串进行MD5摘要加密
22. SHA1加密
public static String sha1(String str) {try {MessageDigest md = MessageDigest.getInstance("SHA1");byte[] bytes = md.digest(str.getBytes("UTF-8"));return toHex(bytes);} catch (Exception e) {throw new RuntimeException(e);}
}
用途:对字符串进行SHA1摘要加密
23. SHA256加密
public static String sha256(String str) {try {MessageDigest md = MessageDigest.getInstance("SHA-256");byte[] bytes = md.digest(str.getBytes("UTF-8"));return toHex(bytes);} catch (Exception e) {throw new RuntimeException(e);}
}
用途:对字符串进行SHA256摘要加密
24. Base64编码
public static String base64Encode(String str) {return Base64.getEncoder().encodeToString(str.getBytes(StandardCharsets.UTF_8));
}
用途:对字符串进行Base64编码
25. Base64解码
public static String base64Decode(String str) {byte[] decodedBytes = Base64.getDecoder().decode(str);return new String(decodedBytes, StandardCharsets.UTF_8);
}
用途:对Base64编码的字符串进行解码
26. AES加密
public static String aesEncrypt(String content, String key) {try {KeyGenerator kgen = KeyGenerator.getInstance("AES");SecureRandom random = SecureRandom.getInstance("SHA1PRNG");random.setSeed(key.getBytes());kgen.init(128, random);SecretKey secretKey = kgen.generateKey();byte[] enCodeFormat = secretKey.getEncoded();SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");Cipher cipher = Cipher.getInstance("AES");cipher.init(Cipher.ENCRYPT_MODE, keySpec);byte[] result = cipher.doFinal(content.getBytes("utf-8"));return Base64.getEncoder().encodeToString(result);} catch (Exception e) {throw new RuntimeException(e);}
}
用途:使用AES算法对字符串进行加密
27. AES解密
public static String aesDecrypt(String content, String key) {try {KeyGenerator kgen = KeyGenerator.getInstance("AES");SecureRandom random = SecureRandom.getInstance("SHA1PRNG");random.setSeed(key.getBytes());kgen.init(128, random);SecretKey secretKey = kgen.generateKey();byte[] enCodeFormat = secretKey.getEncoded();SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");Cipher cipher = Cipher.getInstance("AES");cipher.init(Cipher.DECRYPT_MODE, keySpec);byte[] result = cipher.doFinal(Base64.getDecoder().decode(content));return new String(result, "utf-8");} catch (Exception e) {throw new RuntimeException(e);}
}
用途:使用AES算法对加密字符串进行解密
28. DES加密
public static String desEncrypt(String content, String key) {try {SecureRandom random = new SecureRandom();DESKeySpec desKey = new DESKeySpec(key.getBytes());SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");SecretKey securekey = keyFactory.generateSecret(desKey);Cipher cipher = Cipher.getInstance("DES");cipher.init(Cipher.ENCRYPT_MODE, securekey, random);byte[] result = cipher.doFinal(content.getBytes("utf-8"));return Base64.getEncoder().encodeToString(result);} catch (Exception e) {throw new RuntimeException(e);}
}
用途:使用DES算法对字符串进行加密
29. DES解密
public static String desDecrypt(String content, String key) {try {SecureRandom random = new SecureRandom();DESKeySpec desKey = new DESKeySpec(key.getBytes());SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");SecretKey securekey = keyFactory.generateSecret(desKey);Cipher cipher = Cipher.getInstance("DES");cipher.init(Cipher.DECRYPT_MODE, securekey, random);byte[] result = cipher.doFinal(Base64.getDecoder().decode(content));return new String(result, "utf-8");} catch (Exception e) {throw new RuntimeException(e);}
}
用途:使用DES算法对加密字符串进行解密
30. URL编码
public static String urlEncode(String str) {try {return URLEncoder.encode(str, "UTF-8");} catch (UnsupportedEncodingException e) {throw new RuntimeException(e);}
}
用途:对字符串进行URL编码
文件操作相关(31-50)
31. 计算文件MD5值
public static String getFileMD5(File file) {try (FileInputStream fis = new FileInputStream(file);BufferedInputStream bis = new BufferedInputStream(fis)) {MessageDigest md = MessageDigest.getInstance("MD5");byte[] buffer = new byte[8192];int length;while ((length = bis.read(buffer)) != -1) {md.update(buffer, 0, length);}byte[] bytes = md.digest();return toHex(bytes);} catch (Exception e) {throw new RuntimeException(e);}
}
用途:计算指定文件的MD5摘要值
32. 读取文件内容为字符串
public static String readFileToString(File file) {try {return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);} catch (IOException e) {throw new RuntimeException(e);}
}
用途:将整个文件内容读取为字符串
33. 将字符串写入文件
public static void writeStringToFile(String content, File file) {try {Files.write(file.toPath(), content.getBytes(StandardCharsets.UTF_8));} catch (IOException e) {throw new RuntimeException(e);}
}
用途:将字符串内容写入到指定文件
34. 复制文件
public static void copyFile(File source, File dest) {try (FileInputStream fis = new FileInputStream(source);FileOutputStream fos = new FileOutputStream(dest);FileChannel sourceChannel = fis.getChannel();FileChannel destChannel = fos.getChannel()) {destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());} catch (IOException e) {throw new RuntimeException(e);}
}
用途:复制文件从源路径到目标路径
35. 删除文件
public static boolean deleteFile(File file) {return file.delete();
}
用途:删除指定文件
36. 创建目录
public static boolean createDirectory(File dir) {return dir.mkdirs();
}
用途:创建指定目录(包括必要时的父级目录)
37. 获取文件扩展名
public static String getFileExtension(String fileName) {if (fileName == null || fileName.lastIndexOf(".") == -1) {return "";}return fileName.substring(fileName.lastIndexOf(".") + 1);
}
用途:获取文件名的扩展名部分
38. 获取文件名(不含扩展名)
public static String getFileNameWithoutExtension(String fileName) {if (fileName == null) {return null;}int dotIndex = fileName.lastIndexOf(".");return dotIndex == -1 ? fileName : fileName.substring(0, dotIndex);
}
用途:获取不包含扩展名的文件名
39. 获取文件大小
public static long getFileSize(File file) {return file.length();
}
用途:获取指定文件的大小(字节数)
40. 判断文件是否存在
public static boolean isFileExists(File file) {return file.exists();
}
用途:检查指定文件是否存在
41. 列出目录下的所有文件
public static File[] listFiles(File directory) {return directory.listFiles();
}
用途:列出指定目录下的所有文件和子目录
42. 递归列出目录下的所有文件
public static List<File> listAllFiles(File directory) {List<File> fileList = new ArrayList<>();if (directory.isDirectory()) {File[] files = directory.listFiles();if (files != null) {for (File file : files) {if (file.isFile()) {fileList.add(file);} else if (file.isDirectory()) {fileList.addAll(listAllFiles(file));}}}}return fileList;
}
用途:递归列出指定目录及其子目录下的所有文件
43. 移动文件
public static void moveFile(File source, File dest) {try {Files.move(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);} catch (IOException e) {throw new RuntimeException(e);}
}
用途:移动文件从源路径到目标路径
44. 重命名文件
public static boolean renameFile(File file, String newName) {File newFile = new File(file.getParent(), newName);return file.renameTo(newFile);
}
用途:重命名指定文件
45. 创建临时文件
public static File createTempFile(String prefix, String suffix) {try {return File.createTempFile(prefix, suffix);} catch (IOException e) {throw new RuntimeException(e);}
}
用途:创建临时文件
46. 清空文件内容
public static void clearFile(File file) {try (FileWriter fw = new FileWriter(file, false)) {fw.write("");} catch (IOException e) {throw new RuntimeException(e);}
}
用途:清空指定文件的内容
47. 追加内容到文件
public static void appendToFile(String content, File file) {try (FileWriter fw = new FileWriter(file, true);BufferedWriter bw = new BufferedWriter(fw)) {bw.write(content);bw.newLine();} catch (IOException e) {throw new RuntimeException(e);}
}
用途:向文件末尾追加内容
48. 按行读取文件
public static List<String> readLines(File file) {try {return Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);} catch (IOException e) {throw new RuntimeException(e);}
}
用途:按行读取文件内容到列表
49. 获取文件最后修改时间
public static long getLastModifiedTime(File file) {return file.lastModified();
}
用途:获取文件的最后修改时间戳
50. 设置文件只读属性
public static boolean setReadOnly(File file) {return file.setReadOnly();
}
用途:设置文件为只读属性
日期时间处理相关(51-60)
51. 获取当前时间戳
public static long getCurrentTimestamp() {return System.currentTimeMillis();
}
用途:获取当前系统时间的时间戳(毫秒)
52. 时间戳转日期字符串
public static String timestampToString(long timestamp, String pattern) {SimpleDateFormat sdf = new SimpleDateFormat(pattern);return sdf.format(new Date(timestamp));
}
用途:将时间戳转换为指定格式的日期字符串
53. 日期字符串转时间戳
public static long stringToTimestamp(String dateStr, String pattern) {try {SimpleDateFormat sdf = new SimpleDateFormat(pattern);return sdf.parse(dateStr).getTime();} catch (ParseException e) {throw new RuntimeException(e);}
}
用途:将指定格式的日期字符串转换为时间戳
54. 格式化当前日期时间
public static String getCurrentDateTime(String pattern) {SimpleDateFormat sdf = new SimpleDateFormat(pattern);return sdf.format(new Date());
}
用途:获取格式化的当前日期时间字符串
55. 计算两个日期相差天数
public static int daysBetween(Date startDate, Date endDate) {long diff = endDate.getTime() - startDate.getTime();return (int) (diff / (1000 * 60 * 60 * 24));
}
用途:计算两个日期之间相差的天数
56. 在指定日期上增加天数
public static Date addDays(Date date, int days) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);calendar.add(Calendar.DAY_OF_MONTH, days);return calendar.getTime();
}
用途:在指定日期基础上增加或减少天数
57. 判断是否为闰年
public static boolean isLeapYear(int year) {return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
用途:判断指定年份是否为闰年
58. 获取指定月份的天数
public static int getDaysInMonth(int year, int month) {Calendar calendar = Calendar.getInstance();calendar.set(year, month - 1, 1);return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}
用途:获取指定年月的天数
59. 获取当前星期几
public static String getCurrentWeekDay() {String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};Calendar calendar = Calendar.getInstance();int dayIndex = calendar.get(Calendar.DAY_OF_WEEK) - 1;return weekDays[dayIndex];
}
用途:获取当前是星期几
60. 计算年龄
public static int calculateAge(Date birthDate) {Calendar birth = Calendar.getInstance();birth.setTime(birthDate);Calendar today = Calendar.getInstance();int age = today.get(Calendar.YEAR) - birth.get(Calendar.YEAR);if (today.get(Calendar.DAY_OF_YEAR) < birth.get(Calendar.DAY_OF_YEAR)) {age--;}return age;
}
用途:根据出生日期计算年龄
集合操作相关(61-70)
61. 判断List是否为空
public static boolean isEmpty(List<?> list) {return list == null || list.isEmpty();
}
用途:判断List集合是否为空
62. 判断List是否不为空
public static boolean isNotEmpty(List<?> list) {return !isEmpty(list);
}
用途:判断List集合是否不为空
63. List转数组
public static <T> T[] toArray(List<T> list, Class<T> clazz) {@SuppressWarnings("unchecked")T[] array = (T[]) Array.newInstance(clazz, list.size());return list.toArray(array);
}
用途:将List集合转换为数组
64. 数组转List
public static <T> List<T> toList(T[] array) {return Arrays.asList(array);
}
用途:将数组转换为List集合
65. 合并两个List
public static <T> List<T> mergeLists(List<T> list1, List<T> list2) {List<T> result = new ArrayList<>(list1);result.addAll(list2);return result;
}
用途:合并两个List集合
66. 去除List中的重复元素
public static <T> List<T> removeDuplicates(List<T> list) {return new ArrayList<>(new LinkedHashSet<>(list));
}
用途:去除List集合中的重复元素
67. 反转List
public static <T> void reverseList(List<T> list) {Collections.reverse(list);
}
用途:反转List集合中元素的顺序
68. 对List进行排序
public static <T extends Comparable<? super T>> void sortList(List<T> list) {Collections.sort(list);
}
用途:对List集合进行自然排序
69. 获取Map的所有键
public static <K, V> Set<K> getMapKeys(Map<K, V> map) {return map.keySet();
}
用途:获取Map集合中的所有键
70. 获取Map的所有值
public static <K, V> Collection<V> getMapValues(Map<K, V> map) {return map.values();
}
用途:获取Map集合中的所有值
数字计算相关(71-80)
71. 保留小数位数(四舍五入)
public static double round(double value, int places) {if (places < 0) throw new IllegalArgumentException();BigDecimal bd = new BigDecimal(Double.toString(value));bd = bd.setScale(places, RoundingMode.HALF_UP);return bd.doubleValue();
}
用途:对浮点数进行四舍五入并保留指定小数位数
72. 判断是否为偶数
public static boolean isEven(int number) {return number % 2 == 0;
}
用途:判断整数是否为偶数
73. 判断是否为奇数
public static boolean isOdd(int number) {return number % 2 != 0;
}
用途:判断整数是否为奇数
74. 获取绝对值
public static int abs(int number) {return Math.abs(number);
}
用途:获取整数的绝对值
75. 获取最大值
public static int max(int... numbers) {return Arrays.stream(numbers).max().orElse(0);
}
用途:从一组整数中获取最大值
76. 获取最小值
public static int min(int... numbers) {return Arrays.stream(numbers).min().orElse(0);
}
用途:从一组整数中获取最小值
77. 数字格式化
public static String formatNumber(Number number, String pattern) {DecimalFormat df = new DecimalFormat(pattern);return df.format(number);
}
用途:按照指定模式格式化数字
78. 随机数生成
public static int randomInt(int min, int max) {return new Random().nextInt(max - min + 1) + min;
}
用途:生成指定范围内的随机整数
79. 判断是否为质数
public static boolean isPrime(int number) {if (number <= 1) return false;if (number <= 3) return true;if (number % 2 == 0 || number % 3 == 0) return false;for (int i = 5; i * i <= number; i += 6) {if (number % i == 0 || number % (i + 2) == 0) {return false;}}return true;
}
用途:判断整数是否为质数
80. 计算阶乘
public static long factorial(int n) {if (n < 0) throw new IllegalArgumentException("负数没有阶乘");if (n == 0 || n == 1) return 1;long result = 1;for (int i = 2; i <= n; i++) {result *= i;}return result;
}
用途:计算整数的阶乘
网络请求相关(81-90)
81. 发送GET请求
public static String sendGetRequest(String url) {try {URL obj = new URL(url);HttpURLConnection con = (HttpURLConnection) obj.openConnection();con.setRequestMethod("GET");BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));String inputLine;StringBuilder response = new StringBuilder();while ((inputLine = in.readLine()) != null) {response.append(inputLine);}in.close();return response.toString();} catch (Exception e) {throw new RuntimeException(e);}
}
用途:发送HTTP GET请求并返回响应内容
82. 发送POST请求
public static String sendPostRequest(String url, String postData) {try {URL obj = new URL(url);HttpURLConnection con = (HttpURLConnection) obj.openConnection();con.setRequestMethod("POST");con.setDoOutput(true);try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {wr.writeBytes(postData);wr.flush();}BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));String inputLine;StringBuilder response = new StringBuilder();while ((inputLine = in.readLine()) != null) {response.append(inputLine);}in.close();return response.toString();} catch (Exception e) {throw new RuntimeException(e);}
}
用途:发送HTTP POST请求并返回响应内容
83. 获取本机IP地址
public static String getLocalIpAddress() {try {InetAddress inetAddress = InetAddress.getLocalHost();return inetAddress.getHostAddress();} catch (UnknownHostException e) {throw new RuntimeException(e);}
}
用途:获取本机的IP地址
84. 判断URL是否有效
public static boolean isValidUrl(String url) {try {new URL(url).toURI();return true;} catch (Exception e) {return false;}
}
用途:验证URL格式是否正确
85. URL解析获取域名
public static String getDomainFromUrl(String url) {try {URI uri = new URI(url);return uri.getHost();} catch (URISyntaxException e) {throw new RuntimeException(e);}
}
用途:从URL中提取域名部分
86. 获取网页内容
public static String getWebPageContent(String url) {try {URL website = new URL(url);try (BufferedReader in = new BufferedReader(new InputStreamReader(website.openStream()))) {StringBuilder response = new StringBuilder();String inputLine;while ((inputLine = in.readLine()) != null) {response.append(inputLine);}return response.toString();}} catch (Exception e) {throw new RuntimeException(e);}
}
用途:获取指定URL网页的内容
87. 编码URL参数
public static String encodeUrlParameter(String param) {try {return URLEncoder.encode(param, "UTF-8");} catch (UnsupportedEncodingException e) {throw new RuntimeException(e);}
}
用途:对URL参数进行编码
88. 解码URL参数
public static String decodeUrlParameter(String param) {try {return URLDecoder.decode(param, "UTF-8");} catch (UnsupportedEncodingException e) {throw new RuntimeException(e);}
}
用途:对URL参数进行解码
89. 构建查询字符串
public static String buildQueryString(Map<String, String> params) {StringBuilder sb = new StringBuilder();for (Map.Entry<String, String> entry : params.entrySet()) {if (sb.length() > 0) {sb.append("&");}sb.append(entry.getKey()).append("=").append(encodeUrlParameter(entry.getValue()));}return sb.toString();
}
用途:根据参数Map构建URL查询字符串
90. 解析查询字符串
public static Map<String, String> parseQueryString(String queryString) {Map<String, String> params = new HashMap<>();if (queryString != null && !queryString.isEmpty()) {String[] pairs = queryString.split("&");for (String pair : pairs) {String[] keyValue = pair.split("=");if (keyValue.length == 2) {params.put(decodeUrlParameter(keyValue[0]), decodeUrlParameter(keyValue[1]));}}}return params;
}
用途:解析URL查询字符串为参数Map
其他常用工具(91-100)
91. 生成UUID
public static String generateUUID() {return UUID.randomUUID().toString().replace("-", "");
}
用途:生成全局唯一标识符(UUID)
92. 对象深拷贝
public static <T extends Serializable> T deepCopy(T obj) {try {ByteArrayOutputStream bos = new ByteArrayOutputStream();ObjectOutputStream oos = new ObjectOutputStream(bos);oos.writeObject(obj);oos.flush();oos.close();bos.close();byte[] bytes = bos.toByteArray();ByteArrayInputStream bis = new ByteArrayInputStream(bytes);ObjectInputStream ois = new ObjectInputStream(bis);return (T) ois.readObject();} catch (Exception e) {throw new RuntimeException(e);}
}
用途:实现对象的深度复制
93. 获取系统属性
public static String getSystemProperty(String key) {return System.getProperty(key);
}
用途:获取指定的系统属性值
94. 设置系统属性
public static void setSystemProperty(String key, String value) {System.setProperty(key, value);
}
用途:设置系统属性值
95. 获取环境变量
public static String getEnvVariable(String key) {return System.getenv(key);
}
用途:获取指定的环境变量值
96. 线程休眠
public static void sleep(long milliseconds) {try {Thread.sleep(milliseconds);} catch (InterruptedException e) {Thread.currentThread().interrupt();throw new RuntimeException(e);}
}
用途:使当前线程休眠指定毫秒数
97. 获取当前线程名称
public static String getCurrentThreadName() {return Thread.currentThread().getName();
}
用途:获取当前线程的名称
98. 判断对象是否为null
public static boolean isNull(Object obj) {return obj == null;
}
用途:判断对象是否为null
99. 判断对象是否不为null
public static boolean isNotNull(Object obj) {return !isNull(obj);
}
用途:判断对象是否不为null
100. 执行系统命令
public static String executeCommand(String command) {try {Process process = Runtime.getRuntime().exec(command);BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));StringBuilder output = new StringBuilder();String line;while ((line = reader.readLine()) != null) {output.append(line).append("\n");}process.waitFor();return output.toString();} catch (Exception e) {throw new RuntimeException(e);}
}
用途:执行操作系统命令并返回输出结果