java常用工具类和Hutool常用的工具类整理
1.java常用工具类
1.1 Scanner类
/**
* Scanner 类
*/
@Test
public void testScanner() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个数字: ");
int sc = scanner.nextInt();
System.out.println(sc);
}
1.2Random 类
/**
* Random 类
输出10以内任意一个数
*/
@Test
public void testRandom() {
int random = new Random().nextInt(10);
System.out.println(random);
}
1.3ArrayList类
@Test
public void testArrayList() {
List<Integer> integerList = new ArrayList<>();
integerList.add(1);
integerList.add(2);
integerList.add(3);
/**
* 遍历的方式
*/
// 第一种,传统for循环
System.out.println("第一种,传统for循环");
for (int i = 0; i < integerList.size(); i++) {
int iout = integerList.get(i);
System.out.println(iout);
}
//第二种方式,传统的while循环
System.out.println("第二种方式,传统的while循环");
int i = 0;
while(i < integerList.size()) {
int iout = integerList.get(i);
System.out.println(iout);
i++;
}
//第三中方式,迭代器的for循环的方式
System.out.println("第三中方式,迭代器的for循环的方式");
for(Iterator<Integer> iterator = integerList.iterator();iterator.hasNext();) {
Integer iout = iterator.next();
System.out.println(iout);
}
//第四种,迭代器的while循环方式
System.out.println("第四种,迭代器的while循环方式");
Iterator<Integer> iterator = integerList.iterator();
while(iterator.hasNext()) {
Integer iout = iterator.next();
System.out.println(iout);
}
//第五种方式,foreach方式
System.out.println("第五种方式,foreach方式");
for(Integer iout : integerList) {
System.out.println(iout);
}
//第六种方式,lambda表达式,方法引用,简写方式
System.out.println("第六种方式,lambda表达式,方法引用,简写方式");
integerList.forEach(System.out::println);
//第七种方式,lambda表达式,方法引用
System.out.println("第七种方式,lambda表达式,方法引用");
integerList.forEach(iout->System.out.println(iout));
}
别的集合也可以参照这个方式进行遍历
1.4 collections类
/**
* collections类
* 1.Shuffle(element):洗牌方法,将当前集合内的数据进行随机排序。
2.Reverse(element):逆序排序,对当前集合的元素按照相反的顺序进行排序
3.Sort(element):对当前集合进行升序排序,实现Comparable接口的类,只能使用一种排序方案,这种方案叫作“自然比较”方案。
*/
@Test
public void testCollections() {
/**
* 对集合进行排序
*/
//Integer 类型的集合
List<Integer> list1 = new ArrayList<Integer> ();
list1.add(5);
list1.add(3);
list1.add(4);
list1.add(1);
list1.add(2);
list1.add(2);
System.out.println(list1);
System.out.println("用collections类对集合进行排序");
Collections.sort(list1);
System.out.println(list1);
//String类型的集合 1
System.out.println("\t");
List<String> stringList1 = new ArrayList<String>();
stringList1.add("d");
stringList1.add("c");
stringList1.add("b");
stringList1.add("a");
stringList1.add("a");
System.out.println(stringList1);
Collections.sort(stringList1);
System.out.println("用collections类对集合进行排序");
System.out.println(stringList1);
//String类型的集合
System.out.println("\t");
List<String> stringList2 = new ArrayList<String>();
stringList2.add("哈哈哈哈哈");
stringList2.add("哈哈哈哈");
stringList2.add("哈哈哈");
stringList2.add("哈哈");
stringList2.add("哈");
System.out.println(stringList2);
Collections.sort(stringList2);
System.out.println("用collections类对集合进行排序");
System.out.println(stringList2);
//Reverse(element):逆序排序,对当前集合的元素按照相反的顺序进行排序
System.out.println("Reverse(element):逆序排序,对当前集合的元素按照相反的顺序进行排序");
Collections.reverse(stringList2);
System.out.println(stringList2);
//Shuffle(element):洗牌方法,将当前集合内的数据进行随机排序。
System.out.println("Shuffle(element):洗牌方法,将当前集合内的数据进行随机排序");
Collections.shuffle(stringList2);
System.out.println(stringList2);
}
1.5String类
- 一个操作身份证的示例代码,包含了基本的String类的方法
public class CardNo {
//61011319801012011X
public static void main(String[] args) {
//需求:打印各个部分,确定信息
String cardNo = "61011319801213019X";
//1.地区码
System.out.println("地区码:" + cardNo.substring(0,6));
//2.生日
String year = cardNo.substring(6, 6+4); //编译优化
String month = cardNo.substring(10, 10+2);
month = month.replace("0", "");
String day = cardNo.substring(12, 12+2);
int day1 = Integer.parseInt(day); //自动把前面0去掉
System.out.println("生日:" + year +"年"+month+"月"+day1+"日");
//3.男女
int i = Integer.parseInt(cardNo.substring(cardNo.length()-2, cardNo.length()-1));
String sex = "男";
if(i % 2==0) {
sex = "女";
}
System.out.println("性别:" + sex);
}
}
- 构造方法
- public String () :初始化新创建的 String 对象,以使其表示空字符序列。
- public String (char [] value) :通过当前参数中的字符数组来构造新的 String。
- public String (byte [] bytes) :通过使用平台的默认字符集解码当前参数中的字节数组来构造新的 String。
- string常用方法
- length()字符串的长度
- charAt()截取一个字符
- getchars()截取多个字符并由其他字符串接收
- getBytes () 将字符串变成一个 byte 数组
- toCharArray () 将字符串变成一个字符数组
- equals () 和 equalsIgnoreCase () 比较两个字符串是否相等,前者区分大小写,后者不区分
- startsWith () 和 endsWith () 判断字符串是不是以特定的字符开头或结束
- toUpperCase () 和 toLowerCase () 将字符串转换为大写或小写
- concat () 连接两个字符串
- trim () 去掉起始和结束的空格
- substring()截取字符串
- indexOf () 和 lastIndexOf () 前者是查找字符或字符串第一次出现的地方,后者是查找字符或字符串最后一次出现的地方
- compareTo () 和 compareToIgnoreCase ()按字典顺序比较两个字符串的大小,前者区分大小写,后者不区分
- replace () 替换
- 测试new String(byte[] bytes)和new String(char[] value)
/**
* string 类
* @throws UnsupportedEncodingException 字符集错误
* ISO-8859-1
*/
@Test
public void testString() throws UnsupportedEncodingException {
//测试 new String(byte bytes[], String charsetName)
String str = "helloworld!!!你好世界";
byte[] bytes = str.getBytes();
System.out.println(bytes);
String str1 = new String(bytes,"UTF-8");
System.out.println(str1);
String str2 = new String(bytes);
System.out.println(str2);
String str3 = new String(bytes,"GBK");
System.out.println(str3);
String str4 = new String(bytes,"ISO-8859-1");
System.out.println(str4);
String str5 = new String(bytes,"ASCII");
System.out.println(str5);
String str6 = new String(bytes,"Unicode");
System.out.println(str6);
//测试new String (char [] value) 方法
char[] value = new char[] {'h','e','l','l','o','你','好'};
String strr = new String(value);
System.out.println(strr);
}
- 测试isEmpty()方法
@Test
public void testCollectinsEmpty() {
List<Integer> list1 = new ArrayList<Integer> ();
// list1.add(1);
// list1.add(2);
// list1.add(3);
boolean empty = list1.isEmpty();
System.out.println(empty);
String str2 = "";
boolean empty2 = str2.isEmpty();
System.out.println(empty2);
String str3 = " ";
boolean empty3 = str3.isEmpty();
System.out.println(empty3);
}
-
测试equals () 和 equalsIgnoreCase ()方法
比较两个字符串是否相等,前者区分大小写,后者不区分
@Test
public void testString2() {
/**
* equals () 和 equalsIgnoreCase () 比较两个字符串是否相等,前者区分大小写,后者不区分
*/
String str2 = "Hello World!!!";
String str3 = "hello world!!!";
boolean equals1 = str2.equals(str3);
boolean equals2 = str2.equalsIgnoreCase(str3);
System.out.println(equals1);
System.out.println(equals2);
}
- ==和equals区别
public class String1 {
public static void main(String[] args) {
String s1 = "javaEE";
String s2 = "javaEE";
String s3 = new String("javaEE");
String s4 = new String("javaEE");
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s3 == s4);
System.out.println("equals的比较");
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s3.equals(s4));
}
}
- 证明string的不可变性
public class TestString {
public static void main(String [] args) {
String s = "bb";
TestString t = new TestString();
t.trans(s);
System.out.println(s);
}
public void trans(String s) {
s="aa";
}
}
1.6 Arrays类
/**
* Arrays 类
*/
@Test
public void testArrays() {
// Arrays.asList(T… data)将数组转换为集合
List<Integer> list = Arrays.asList(1, 2, 3);
Integer[] data = { 1, 2, 3 };
List<Integer> list2 = Arrays.asList(data);
// 集合转换数组
// Object[] array = list.toArray();进行强转
Integer[] array = (Integer[]) list.toArray();
// Arrays.fill() 用指定元素填充整个数组(会替换掉数组中原来的元素)
Integer[] data1 = { 1, 2, 3, 4 };
Arrays.fill(data1, 9);
System.out.println(Arrays.toString(data1)); // [9, 9, 9, 9]
// Arrays.sort(),对数组元素进行排序(串行排序
Integer[] data2 = { 3, 2, 1, 5, 3, 8, 9, 1, 3 };
Arrays.sort(data2);
System.out.println(Arrays.toString(data2));
// Arrays.binarySearch () 二分法 查找
/**
* 注意:在调用该方法之前,必须先调用 sort () 方法进行排序,如果数组没有排序,
* 那么结果是不确定的,此外如果数组中包含多个指定元素,则无法保证将找到哪个元素
*/
int binarySearch = Arrays.binarySearch(data2, 9);
System.out.println(binarySearch);
// Arrays.copyOf()数组赋值
/**
* 拷贝数组,其内部调用了 System.arraycopy () 方法,从下标 0 开始,如果超过原数组长度,会用 null 进行填充
*/
Integer[] copyOf = Arrays.copyOf(data2, 4);
System.out.println(Arrays.toString(copyOf));
}
1.7 Math类
// Maths类
/**
- public static long abs (double a): 返回 a 的绝对值。
- public static double max (double a,double b): 返回 a、b 的最大值。
- public static double min (double a,double b): 返回 a、b 的最小值。
- pubic static double random (): 产生一个 0~1 之间的随机数 (不包括 0 和 1)。
- public static double pow (double a,double b); 返回 a 的 b 次幂。
- public static double sqrt (double a): 返回 a 的平方根。
- public static double log (double a): 返回 a 的对数。
- public static double sin (double a): 返回 a 的正弦值。
- public static double asin (double a): 返回 a 的反正弦值。
- public static double ceil (double a): 返回大于 a 的最小整数
- public static double floor (double a): 返回小于 a 的最大整数
public static long round (double a): 返回值是 (long) Math.floor (a+0.5)), 即所谓 a 的 “四舍五入” 后的值
- */
@Test
public void testMath() {
// public static double sqrt (double a): 返回 a 的平方根。
double sqrt = Math.sqrt(4);
System.out.println(sqrt);
//public static double ceil (double a): 返回大于 a 的最小整数
double ceil = Math.ceil(15.44);
System.out.println(ceil);
//public static double floor (double a)
double floor = Math.floor(15.66);
System.out.println(floor);
//public static long round (double a)类似于sql的round函数
long round1 = Math.round(15.444);
long round2 = Math.round(15.666);
System.out.println(round1);
System.out.println(round2);
}
1.8日期时间类,主要是SimpleDateFormat
常用方法:
- public String format (Date date):将 Date 对象格式化为字符串。
- public Date parse (String source):将字符串解析为 Date 对象。
/**
* java.util.Date类转为String类型 12小时时间制
*/
@Test
public void testSimpleDateFormat1() {
//说明:如果是mm是12小时制度
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String dateString = simpleDateFormat.format(new Date());
System.out.println(dateString);
// 此时是下午的14.55.53,以下使用的是12小时时间制
// 控制台输出:
// 2020-08-19 02:55:53
}
/**
* java.util.Date类转为String类型 24小时时间制
* 注意:一般都是24小时制度的,所以最好记住格式 yyyy-MM-dd HH:mm:ss
*/
@Test
public void testSimpleDateFormat2() {
//说明:如果是MM是24小时制度
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = simpleDateFormat.format(new Date());
// 此时是下午的14.55.53,以下使用的是12小时时间制
// 控制台输出:
// 2020-08-19 14:55:53
}
/**
* 获取时间格式为20200000的格式,数字之间没有连接符
*/
@Test
public void testSimpleDateFormat3() {
//说明:如果是mm是12小时制度
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String dateString = simpleDateFormat.format(new Date());
System.out.println(dateString);
// 此时是下午的14.55.53,以下使用的是12小时时间制
// 控制台输出:
// 20200819174003
}
/**
* SimpleDateFormat的parse方法把字符窜时间格式转换为java.lang.Date
* @throws ParseException
*/
@Test
public void testSimpleDateFormat4() throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date strToDate= simpleDateFormat.parse("2020-08-19 14:55:53");
System.out.println(strToDate);
}
1.9 System 类
- currentTimeMillis 方法:毫秒级的时间戳
- arrayCopy 方法:将数组中指定的数据拷贝到另一个数组中。System.arraycopy( 源数组, 源数组, 目标数组, 目标数组索引起始位置, length);
/**
* System 类
*/
@Test
public void testSystem() {
long start = System.currentTimeMillis();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("花费时间"+ (end-start));
}
1.10 StringBuilder类
构造方法:
- public StringBuilder ():构造一个空的 StringBuilder 容器。
- public StringBuilder (String str):构造一个 StringBuilder 容器,并将字符串添加进去。
常用方法
- public StringBuilder append (…):添加任意类型数据的字符串形式,并返回当前对象自身。
- public String toString ():将当前 StringBuilder 对象转换为 String 对象。
/**
* StringBuilder 类
* 由于 String 类的对象内容不可改变,所以每当进行字符串拼接时,总是会在内存中创建一个新的对象。 在 API 中对
* String 类有这样的描述:字符串是常量,它们的值在创建后不能被更改。为了解决这一问题,可以使用 java.lang.StringBuilder 类。
*/
@Test
public void testStringBuilder() {
StringBuilder sb = new StringBuilder("hello ");
sb.append("world");
System.out.println(sb);
}
1.11 包装类
Integer i = new Integer(4);//使用构造函数函数
Integer iii = Integer.valueOf(4);//使用包装类中的valueOf方法
2.hutool工具类中常用方法
使用方法
maven项目在pom.xml添加以下依赖即可:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.6.3</version>
</dependency>
常用工具类
补充:
java中数字与字符串之间互相转换
/**
* java中字符串和数值互相转换
*/
@Test
public void testNumAndString() {
Integer i = 1;
String str = "111";
//数字转字符窜
String numToString = String.valueOf(i);
System.out.println(numToString);
//字符窜转时间
int parseInt = Integer.parseInt(str);
System.out.println(parseInt);
}
2.1.Convert
@Test
public void test1() {
// 转换为字符串
int a = 1;
String aStr = Convert.toStr(a);
// 转换为指定类型数组
String[] b = { "1", "2", "3", "4" };
Integer[] bArr = Convert.toIntArray(b);
// 转换为日期对象
String dateStr = "2017-05-06";
Date date = Convert.toDate(dateStr);
// 转换为列表
String[] strArr = { "a", "b", "c", "d" };
List<String> strList = (List<String>) Convert.toList(String.class, strArr);
}
2.2.DateUtil
//Date、long、Calendar之间的相互转换
//当前时间
Date date = DateUtil.date();
//Calendar转Date
date = DateUtil.date(Calendar.getInstance());
//时间戳转Date
date = DateUtil.date(System.currentTimeMillis());
//自动识别格式转换
String dateStr = "2017-03-01";
date = DateUtil.parse(dateStr);
//自定义格式化转换
date = DateUtil.parse(dateStr, "yyyy-MM-dd");
//格式化输出日期
String format = DateUtil.format(date, "yyyy-MM-dd");
//获得年的部分
int year = DateUtil.year(date);
//获得月份,从0开始计数
int month = DateUtil.month(date);
//获取某天的开始、结束时间
Date beginOfDay = DateUtil.beginOfDay(date);
Date endOfDay = DateUtil.endOfDay(date);
//计算偏移后的日期时间
Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
//计算日期时间之间的偏移量
long betweenDay = DateUtil.between(date, newDate, DateUnit.DAY);
2.3.StrUtil
//判断是否为空字符串
String str = "test";
StrUtil.isEmpty(str);
StrUtil.isNotEmpty(str);
//去除字符串的前后缀
StrUtil.removeSuffix("a.jpg", ".jpg");
StrUtil.removePrefix("a.jpg", "a.");
//格式化字符串
String template = "这只是个占位符:{}";
String str2 = StrUtil.format(template, "我是占位符");
LOGGER.info("/strUtil format:{}", str2);
2.4.ClassPathResource
获取classPath下的文件,在Tomcat等容器下,classPath一般是WEB-INF/classes。
//获取定义在src/main/resources文件夹中的配置文件
ClassPathResource resource = new ClassPathResource("generator.properties");
Properties properties = new Properties();
properties.load(resource.getStream());
LOGGER.info("/classPath:{}", properties);
测试代码
- generator.properties文件内容
username=root
password=123456
chinese=是否可以获取中文+hellowrold
- 测试代码
public class TestHutoolClassPathResource {
@Test
public void test1() throws NoResourceException, IOException {
ClassPathResource resource = new ClassPathResource("generator.properties");
Properties properties = new Properties();
properties.load(resource.getStream());
System.out.println(properties);
}
}
- 控制台输出
{password=123456, chinese=是å¦å¯ä»¥èŽ·å–ä¸æ–‡+hellowrold, username=root}
说明:
properties文件的value不能是英文
2.5.ReflectUtil
- 测试反射的pojo类,有私有属性,有私有方法
package com.shaoming.hutool工具类的测试方法;
public class Hello {
private String privatev = "private私用属性的值";
public String publicv = "public属性的值";
private Integer id;
public Hello() {
super();
}
public Hello(String privatev, String publicv, Integer id) {
super();
this.privatev = privatev;
this.publicv = publicv;
this.id = id;
}
public String getPrivatev() {
return privatev;
}
public void setPrivatev(String privatev) {
this.privatev = privatev;
}
public String getPublicv() {
return publicv;
}
public void setPublicv(String publicv) {
this.publicv = publicv;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String toString() {
return "Hello [privatev=" + privatev + ", publicv=" + publicv + ", id=" + id + "]";
}
/**
* 私用方法
*/
private String privateReturn(String str) {
return str;
}
public String publicReturn(String str) {
return str;
}
}
- 测试
/**
* ReflectUtil
*/
@Test
public void test2() {
获取某个类的所有方法
Method[] methods = ReflectUtil.getMethods(Hello.class);
System.out.println(Arrays.toString(methods));
//获取某个类的指定方法
Method method = ReflectUtil.getMethod(Hello.class,"privateReturn");
System.out.println(method);
//使用反射来创建对象
Hello hello = ReflectUtil.newInstance(Hello.class);
//反射执行对象的方法
Object invoke = ReflectUtil.invoke(hello, "privateReturn", "privateString的值");
System.out.println(invoke);
//获取属性
Field[] fields = ReflectUtil.getFields(Hello.class);
System.out.println(Arrays.toString(fields));
//获取构造器
Constructor<Hello>[] constructors = ReflectUtil.getConstructors(Hello.class);
System.out.println(Arrays.toString(constructors));
}
2.6NumberUtil
double n1 = 1.234;
double n2 = 1.234;
double result;
//对float、double、BigDecimal做加减乘除操作
result = NumberUtil.add(n1, n2);
result = NumberUtil.sub(n1, n2);
result = NumberUtil.mul(n1, n2);
result = NumberUtil.div(n1, n2);
//保留两位小数
BigDecimal roundNum = NumberUtil.round(n1, 2);
String n3 = “1.234”;
//判断是否为数字、整数、浮点数
NumberUtil.isNumber(n3);
NumberUtil.isInteger(n3);
NumberUtil.isDouble(n3);
/**
* 对数值操作
* 加减乘除
* NumberUtil.add 针对double类型做加法
NumberUtil.sub 针对double类型做减法
NumberUtil.mul 针对double类型做乘法
NumberUtil.div 针对double类型做除法,并提供重载方法用于规定除不尽的情况下保留小数位数和舍弃方式。
*/
@Test
public void test17() {
Double d1 = 0.05 ;
Double d2 = 0.01;
System.out.println(d1+d2);
System.out.println(0.05 + 0.01);
//使用Hutool的工具类
System.out.println("使用hutoo的工具类之后");
double hutooladd = NumberUtil.add(d1,d2);
System.out.println(hutooladd);
}
/**
* 测试NumberUtil的div方法,测试保留几位小数
* /**
* 提供(相对)精确的除法运算,当发生除不尽的情况时,由scale指定精确度,后面的四舍五入
*
* @param v1 被除数
* @param v2 除数
* @param scale 精确度,如果为负值,取绝对值
* @return 两个参数的商
public static double div(float v1, float v2, int scale) {
return div(v1, v2, scale, RoundingMode.HALF_UP);
}
*/
@Test
public void test18() {
Double d1 = 1.0;
Double d2 = 3.0;
//测试保留两位小数
double div = NumberUtil.div(d1, d2,2);
System.out.println(div);
}
//保留小数,
@Test
public void test19() {
//这种方法没有四舍五入
Double d = 1.23456789;
//保留三位小数
System.out.println(NumberUtil.round(d, 3));
//保留四位小数
System.out.println(NumberUtil.round(d, 7));
//NumberUtil.roundStr 方法主要封装String.format方法,舍弃方式采用四舍五入。
double te1=123456.123456;
double te2=123456.128456;
Console.log(NumberUtil.roundStr(te1,2));//结果:123456.12
Console.log(NumberUtil.roundStr(te2,2));//结果:123456.13
}
2.7FileUtil
//FileUtil
/**
* 在FileUtil中,我努力将方法名与Linux相一致,例如创建文件的方法并不是createFile,而是touch,这种统一对于熟悉Linux的人来说,大大提高了上手速度。当然,如果你不熟悉Linux,那FileUtil工具类的使用则是在帮助你学习Linux命令。这些类Linux命令的方法包括:
ls 列出目录和文件
touch 创建文件,如果父目录不存在也自动创建
mkdir 创建目录,会递归创建每层目录
del 删除文件或目录(递归删除,不判断是否为空),这个方法相当于Linux的delete命令
copy 拷贝文件或目录
*/
//touch 创建文件
@Test
public void test9() {
File file = FileUtil.touch("G:/myfile/java/Hello.java");
System.out.println(file);
}
//ls 查看文件列表
@Test
public void test10() {
File[] ls = FileUtil.ls("G:/");
System.out.println(Arrays.toString(ls));
}
//mkdir 创建文件
@Test
public void test11() {
File mkdir = FileUtil.mkdir("G:/myfile/java");
System.out.println(mkdir);
}
//del 删除文件
@Test
public void test12() {
FileUtil.del("G:/myfile");
}
//文件类型判断
@Test
public void test13() {
File file = FileUtil.file("G:/myfile/java/Hello.java");
String type = FileTypeUtil.getType(file);
//输出 jpg则说明确实为jpg文件
Console.log(type);
}
//文件读取
@Test
public void test14() {
//默认UTF-8编码,可以在构造中传入第二个参数做为编码
FileReader fileReader = new FileReader("G:/myfile/java/my.txt");
String result = fileReader.readString();
System.out.println(result);
}
//文件写入
@Test
public void test15() {
FileWriter writer = new FileWriter("G:/myfile/java/Hello.java");
writer.write(" public class Hello {\r\n" +
"\r\n" +
" public static void main(String[] args) {\r\n" +
" //单行注释\r\n" +
" /*\r\n" +
" * 多行注释\r\n" +
" */\r\n" +
" /**\r\n" +
" * 文档注释\r\n" +
" */\r\n" +
" System.out.println(\"hello world!!!\");\r\n" +
"\r\n" +
" }\r\n" +
"\r\n" +
"}");
}
//文件追加
@Test
public void test16() {
File file = new File("G:/myfile/java/my.txt");
FileAppender appender = new FileAppender(file, 16, true);
appender.append("123");
appender.append("abc");
appender.append("xyz");
appender.flush();
appender.toString();
}
2.8MapUtil
/**
* MapUtil
*/
@Test
public void testMapUtil() throws Exception {
//将多个键值对加入到Map中
Map<Object, Object> map = MapUtil.of(new String[][]{
{"key1", "value1"},
{"key2", "value2"},
{"key3", "value3"}
});
System.out.println(map);
//判断Map是否为空
MapUtil.isEmpty(map);
MapUtil.isNotEmpty(map);
}
2.9BeanUtil
/**
* BeanUtil
*/
@Test
public void testBeanUtil() throws Exception {
Hello hello = new Hello();
hello.setId(1);
hello.setPrivatev("private属性的值");
hello.setPublicv("public属性的值");
Bean转Map
Map<String, Object> beanToMap = BeanUtil.beanToMap(hello);
System.out.println(beanToMap);
//Map转Bean
Hello mapToBean = BeanUtil.mapToBean(beanToMap, Hello.class, false);
System.out.println(mapToBean);
}
2.10 CollUtil
/**
* SecureUtil
*/
@Test
public void testSecureUtil() throws Exception {
//MD5加密
String str = "123456";
String md5Str = SecureUtil.md5(str);
Console.log(md5Str);
}
2.11 JSONUtil
/**
* json工具类
*/
//快速创建一个json格式的字符窜
@Test
public void test21() {
JSONObject json1 = JSONUtil.createObj()
.put("a", "value1")
.put("b", "value2")
.put("c", "value3");
System.out.println(json1);
String jsonStr = "{\"b\":\"value2\",\"c\":\"value3\",\"a\":\"value1\"}";
Console.log(jsonStr);
}
//java对象转为json格式的字符窜
@Test
public void test22() {
UserA userA = new UserA();
userA.setName("nameTest");
//DateUtil.date()返回当前时间
userA.setDate(new Date());
userA.setSqs(CollectionUtil.newArrayList(new Seq(null), new Seq("seq2")));
// false表示不跳过空值
JSONObject json = JSONUtil.parseObj(userA, false);
//没有美化的json
Console.log(json.toString());
//美化json格式的字符窜
Console.log(json.toStringPretty());
}
3.参考网址
java常用api
https://mp.weixin.qq.com/s?__biz=MzAwMjk5Mjk3Mw==&mid=2247491994&idx=3&sn=64eeed8938d8f75df1bd70b0fff10f58&chksm=9ac35fb8adb4d6aea70752d80221ef42e09c3d57b3e507dcba604c0f076c442b886198039280&mpshare=1&scene=1&srcid=0829lSf29NuszHMa9dJ48LLf&sharer_sharetime=1598681791618&sharer_shareid=9d1e76e919cc0b2f3ca23ed1f5ef67a8&key=b0e41fc55fd7ea00a46378d37b19d0f4b2a7fc4ea991736e5ac74fc2777d43bb834576edf9eb940bb3bf85aa6c38ef8b4cd313b080ccad30eebcad6d6513d1ea5823eebe18e72b0c93cf244ffe6079ba8b154167d101c291b132beea371b57375ec4ff730805c9a5a04b4c00496f3104fdb20a792bb07b05e4fd998e5f8de37e&ascene=1&uin=NjU1MDkwNDgx&devicetype=Windows+10+x64&version=62090529&lang=zh_CN&exportkey=AQgSAOSNKvBxrIWYiAgkBxM%3D&pass_ticket=vCGOc5PV%2Fd1fa%2FlpgYKeqodi4lxvMCccnYJaeULq5IyQonzKJTFniDc2qj1Of6Z%2F
hutool工具类 常用的方法
https://mp.weixin.qq.com/s?__biz=MzA3ODQ0Mzg2OA==&mid=2649050755&idx=3&sn=75c7d04cf28efdebdb68a304ed23dc9d&chksm=87534ab0b024c3a62dc398ce4eb3c5c270c89f742b220ba1e5a4ca250e8b69f055f6c3bf25b3&mpshare=1&scene=1&srcid=0829U3rR3Ehqd0jMfQ8gh4ga&sharer_sharetime=1598682231601&sharer_shareid=9d1e76e919cc0b2f3ca23ed1f5ef67a8&key=b0e41fc55fd7ea00eceef072050b43d492c8c61583bf6eae6715fc5c8dbbb1c22bfc37918da7a95b49c48481f3f633982e95a1504c47e153f0bf0e1826eced70a41ebcac535d62652cbf1eec587b372dfdc85a6a96befe5d8f410efdd4004e9532ceea4bd4036ef68f7fd31b6cf179b59bb70bffbe0b9ed609ab0f4660f6c122&ascene=1&uin=NjU1MDkwNDgx&devicetype=Windows+10+x64&version=62090529&lang=zh_CN&exportkey=AUkJx%2BFZ5mQS4SDCnOFGJaw%3D&pass_ticket=vCGOc5PV%2Fd1fa%2FlpgYKeqodi4lxvMCccnYJaeULq5IyQonzKJTFniDc2qj1Of6Z%2F