工具类
- 工具类无需创建对象就能使用,可以直接使用类中的属性和方法,一般都声明为静态
- 工具类对外提供的属性和方法都是公共的
- 提供丰富的方法和属性
自定义String工具类 -- StringUtil
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
public class Util {
public static void main(String[] args) throws Exception {
System.out.println(StringUtil.isEmpty(null)); //true
System.out.println(StringUtil.isEmpty("")); //true
System.out.println(StringUtil.isEmpty(" "));//true
System.out.println(StringUtil.isEmpty("abc")); //false
System.out.println(StringUtil.makeString());
System.out.println(StringUtil.makeString("abcdefg123456", 6));
System.out.println(StringUtil.formatDate(new Date(), "yyyy-MM-dd"));
System.out.println(StringUtil.parseDate("2022-01-03", "yyyy-MM-dd"));
}
}
//字符串工具类
class StringUtil{
//字符串非空判断
public static boolean isEmpty(String str){
//字符串为null
// if (str==null) {
// return true;
// }
// //字符串为空字符串
// if ("".equals(str)) {
// return true;
// }
// //字符串全为空格 -- .trim()方法去除字符串中的空格
// if ("".equals(str.trim())) {
// return true;
// }
//合并三个判断
if (str == null || "".equals(str.trim())) {
return true;
}
return false;
}
public static boolean isNotEmpty(String str){
//直接调用
return !isEmpty(str);
}
//生成随机字符串
public static String makeString(){
//UUID类提供了字符串的随机生成 -- 伪随机 与当前时间戳相关
return UUID.randomUUID().toString();
}
//从给定字符串中随机获取字符形成随机字符串
public static String makeString(String from,int len){
if ( len < 1 ) {
return "";
}else{
//获取字符串中的所有字符
char[] chars = from.toCharArray();
//StringBuilder 可变的字符序列 提供增加、删除字符串中字符等方法
StringBuilder str = new StringBuilder();
for (int i = 0; i < len; i++) {
//Random类提供随机生成数组、字符等方法
Random random = new Random();
//传入的实参chars.length限定随机数的范围
int t = random.nextInt(chars.length);
char c = chars[t];
//StringBuilder.append() 字符串拼接
str.append(c);
}
return str.toString();
}
}
//转换字符串:IS08859-1 => str => UTF-8
public static String transform(String source, String encodeForm, String encodeTo) throws Exception{
//.getBytes方法 可以从指定编码中获取字符
byte[] bytes = source.getBytes(encodeForm);
//String构造方法 可以将字符数组转换为指定编码的字符串
return new String(bytes,encodeTo);
}
//将字符串转换为指定格式的日期
public static Date parseDate(String dateString, String format) throws Exception{
//SimpleDateFormat类 可以根据字符串格式创建日期对象 -- 对象的一个属性
SimpleDateFormat sdf = new SimpleDateFormat(format);
//日期对象的.parse()方法 可以将字符串转换为指定格式(对象创建时的属性)
return sdf.parse(dateString);
}
//将指定格式的日期转换为字符串
public static String formatDate(Date date, String format) throws Exception{
//SimpleDateFormat类 可以根据字符串格式创建日期对象 -- 对象的一个属性
SimpleDateFormat sdf = new SimpleDateFormat(format);
//日期对象的.format()方法 可以将指定格式的日期转换为字符串
return sdf.format(date);
}
}
标签:return,String,public,str,字符串,工具,StringUtil
From: https://www.cnblogs.com/Ashen-/p/17021279.html