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