以下是一些常用的Java快捷方法:

  1. 判断字符串是否为空或null:
public static boolean isNullOrEmpty(String str) {
    return str == null || str.trim().isEmpty();
}
  1. 判断数组是否为空或null:
public static boolean isNullOrEmpty(Object[] arr) {
    return arr == null || arr.length == 0;
}
  1. 判断集合是否为空或null:
public static boolean isNullOrEmpty(Collection<?> collection) {
    return collection == null || collection.isEmpty();
}
  1. 拷贝文件:
public static void copyFile(File source, File destination) throws IOException {
    Files.copy(source.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
  1. 读取文件内容:
public static String readFile(File file) throws IOException {
    return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
}
  1. 将字符串转换为日期:
public static Date parseDate(String strDate, String dateFormat) throws ParseException {
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
    return formatter.parse(strDate);
}
  1. 将日期转换为字符串:
public static String formatDate(Date date, String dateFormat) {
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
    return formatter.format(date);
}
  1. 获取当前时间戳:
public static long getCurrentTimestamp() {
    return System.currentTimeMillis();
}
  1. 获取当前时间字符串:
public static String getCurrentTimeString(String dateFormat) {
    Date now = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
    return formatter.format(now);
}
  1. 获取文件后缀名:
public static String getFileExtension(String fileName) {
    int dotIndex = fileName.lastIndexOf('.');
    return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
}
编写Java的一些快捷方法

原文地址: https://www.cveoy.top/t/topic/bHpW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录