public class CheckUtils {
/**
* 判断字符串是否为空或 null
* @param str 待判断的字符串
* @return 如果字符串为空或 null,则返回 true;否则返回 false
*/
public static boolean isEmpty(String str) {
return str == null || str.isEmpty();
}
/**
* 判断对象是否为空或 null
* @param obj 待判断的对象
* @return 如果对象为空或 null,则返回 true;否则返回 false
*/
public static boolean isNull(Object obj) {
return obj == null;
}
/**
* 判断数字是否大于等于零
* @param num 待判断的数字
* @return 如果数字大于等于零,则返回 true;否则返回 false
*/
public static boolean isPositive(int num) {
return num >= 0;
}
/**
* 判断集合是否为空或 null
* @param collection 待判断的集合
* @param <T> 集合中元素的类型
* @return 如果集合为空或 null,则返回 true;否则返回 false
*/
public static <T> boolean isEmpty(Collection<T> collection) {
return collection == null || collection.isEmpty();
}
/**
* 判断数组是否为空或 null
* @param array 待判断的数组
* @param <T> 数组中元素的类型
* @return 如果数组为空或 null,则返回 true;否则返回 false
*/
public static <T> boolean isEmpty(T[] array) {
return array == null || array.length == 0;
}
/**
* 判断文件是否存在或可读等
* @param file 待判断的文件
* @return 如果文件存在且可读,则返回 true;否则返回 false
*/
public static boolean isFileValid(File file) {
return file != null && file.exists() && file.canRead();
}
/**
* 判断网络是否可用
* @return 如果网络可用,则返回 true;否则返回 false
*/
public static boolean isNetworkAvailable() {
try {
InetAddress.getByName("www.google.com");
return true;
} catch (UnknownHostException e) {
return false;
}
}
/**
* 校验手机号码格式是否正确
* @param phone 手机号码
* @return 如果手机号码格式正确,则返回 true;否则返回 false
*/
public static boolean isValidPhone(String phone) {
if (isEmpty(phone)) {
return false;
}
String regex = "^1[0-9]{10}$";
return phone.matches(regex);
}
/**
* 校验身份证号码格式是否正确
* @param idCard 身份证号码
* @return 如果身份证号码格式正确,则返回 true;否则返回 false
*/
public static boolean isValidIdCard(String idCard) {
if (isEmpty(idCard)) {
return false;
}
String regex = "^[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2]\\d|3[0-1])\\d{3}[0-9Xx]$";
return idCard.matches(regex);
}
/**
* 校验邮箱地址格式是否正确
* @param email 邮箱地址
* @return 如果邮箱地址格式正确,则返回 true;否则返回 false
*/
public static boolean isValidEmail(String email) {
if (isEmpty(email)) {
return false;
}
String regex = "^[A-Za-z0-9]+([._\\-]*[A-Za-z0-9])*@([A-Za-z0-9]+[-.])+[A-Za-z]{2,}$";
return email.matches(regex);
}
}
Java中CheckUtils工具类里的方法及代码示例
于 2023-04-24 10:40:20 首次发布