获取类名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 外部普通类
System.out.println("方法名 类名");
System.out.println("getName " + TestClass.class.getName());
System.out.println("getCanonicalName " + TestClass.class.getCanonicalName());
System.out.println("getSimpleName " + TestClass.class.getSimpleName());
System.out.println();

// 内部类
System.out.println("getName " + TestInnerClass.class.getName());
System.out.println("getCanonicalName " + TestInnerClass.class.getCanonicalName());
System.out.println("getSimpleName " + TestInnerClass.class.getSimpleName());
System.out.println();

// 数组类
TestInnerClass[] testInnerClasses = new TestInnerClass[]{
new TestInnerClass(),
new TestInnerClass(),
new TestInnerClass()
};
System.out.println("getName " + testInnerClasses.getClass().getName());
System.out.println("getCanonicalName " + testInnerClasses.getClass().getCanonicalName());
System.out.println("getSimpleName " + testInnerClasses.getClass().getSimpleName());
System.out.println();

输出

1
2
3
4
5
6
7
8
9
10
11
12
方法名              类名
getName com.test.TestClass
getCanonicalName com.test.TestClass
getSimpleName TestClass

getName com.test.TestClass$TestInnerClass
getCanonicalName com.test.TestClass.TestInnerClass
getSimpleName TestInnerClass

getName [Lcom.test.TestClass$TestInnerClass;
getCanonicalName com.test.TestClass.TestInnerClass[]
getSimpleName TestInnerClass[]

获取项目绝对路径

1
System.getProperty("user.dir")

遍历树形结构

https://mp.weixin.qq.com/s/xhrcvRRBEWEBMZ86-YsZag

  1. 实体类:Menu.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Menu {
/**
* id
*/
public Integer id;
/**
* 名称
*/
public String name;
/**
* 父id ,根节点为0
*/
public Integer parentId;
/**
* 子节点信息
*/
public List<Menu> childList;


public Menu(Integer id, String name, Integer parentId) {
this.id = id;
this.name = name;
this.parentId = parentId;
}

public Menu(Integer id, String name, Integer parentId, List<Menu> childList) {
this.id = id;
this.name = name;
this.parentId = parentId;
this.childList = childList;
}
}
  1. 遍历数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@Test
public void testtree(){
//模拟从数据库查询出来
List<Menu> menus = Arrays.asList(
new Menu(1,"根节点",0),
new Menu(2,"子节点1",1),
new Menu(3,"子节点1.1",2),
new Menu(4,"子节点1.2",2),
new Menu(5,"根节点1.3",2),
new Menu(6,"根节点2",1),
new Menu(7,"根节点2.1",6),
new Menu(8,"根节点2.2",6),
new Menu(9,"根节点2.2.1",7),
new Menu(10,"根节点2.2.2",7),
new Menu(11,"根节点3",1),
new Menu(12,"根节点3.1",11)
);

//获取父节点
List<Menu> collect = menus.stream().filter(m -> m.getParentId() == 0).map(
(m) -> {
m.setChildList(getChildrens(m, menus));
return m;
}
).collect(Collectors.toList());
System.out.println("-------转json输出结果-------");
System.out.println(JSON.toJSON(collect));
}

/**
* 递归查询子节点
* @param root 根节点
* @param all 所有节点
* @return 根节点信息
*/
private List<Menu> getChildrens(Menu root, List<Menu> all) {
List<Menu> children = all.stream().filter(m -> {
return Objects.equals(m.getParentId(), root.getId());
}).map(
(m) -> {
m.setChildList(getChildrens(m, all));
return m;
}
).collect(Collectors.toList());
return children;
}

遍历文件夹

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 public static void main(String[] args) {
String rootPath = "/Users/wangwz/IdeaProjects/ws-zhzf2-shanxi/scm/scm-web/src/main/webapp";
File files = new File(rootPath);
print(files);
}

private static void print(File files) {
File[] listFiles = files.listFiles();
for (File file : listFiles) {
if(file.isDirectory()) {
//目录
print(file);
} else {
//文件
System.out.println(file.getName());
}
}
}

判断网络资源是否存在

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private static boolean bResourceExist(String urlname) {
URL url;
try {
url = new URL(urlname);
// 返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。
URLConnection uc = url.openConnection();
// 打开的连接读取的输入流。
InputStream in = uc.getInputStream();
return true;
} catch (Exception e) {
url = null;
return false;
}
}
public static void main(String[] args) {
boolean b = bResourceExist("http://115.28.211.11/demo/202006090112-%E6%96%B0%E7%AB%8B%E6%A1%88%E9%80%9A%E7%9F%A5%E4%B9%A6.pdf");
System.out.println("b = " + b);
}

BigDecimal 与 double 互转

1
2
3
4
5
6
//double 转 BigDecimal
BigDecimal bigDecimal = new BigDecimal("22.234533433"); //存在精确损失-不建议使用
BigDecimal bigDecimal = BigDecimal.valueOf(12.39979783838); //推荐使用

//BigDecimal 转 double
double doubleVal = bigDecimal.doubleValue();

反射

https://zhuanlan.zhihu.com/p/73710795

从对象获取字段值

  1. 获取 Class

    • Class stuClass = Student.class;
      
      1
      2
      3
      4

      * ```java
      Student stu = new Student();
      Class stuClass = stu.getClass();
    • Class stuClass = Class.forName(”fanshe.Student”);
      
      1
      2
      3
      4
      5

      2. 获取字段 Field

      ```java
      Field nameField = stuClass.getDeclaredField("name");
  2. 获取字段值

    1
    2
    nameField.setAccessible(true);
    String name = (String) nameField.get(stu);

批量操作「分页」

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//批量值:单次操作数量
final int BATCH_SIZE = 50000;

//获取实际总数量
int total = this.xxxDao.selectCount();

//批量操作次数
int count = total/ BATCH_SIZE + 1;

int start;
int end;
for (int i = 0; i < count; i++) {
start = i* BATCH_SIZE;
end = (i+1)* BATCH_SIZE;
if(end > total) {
end = total;
}
// 以下为批量操作代码
}

字符串操作

去掉字符串开头的所有空格

1
2
3
4
5
import org.springframework.util.StringUtils;

String str = " 这是一个带有空格的字符串。";
str = StringUtils.trimLeadingWhitespace(str);
System.out.println(str);

字符串截取 substring

1
2
3
4
String point = "34.90364646664826,108.94620186992519;34.88785743713379,108.93914222717285";
System.out.println(point.substring(0, point.indexOf(";")));

// 34.90364646664826,108.94620186992519

分隔字符串 split

1
2
3
4
5
6
7
8
9
10
11
String s = "楼栋1, 楼栋2,楼栋3,楼栋4 ,楼栋5 ";
String[] split = s.split(",|,"); //根据英文或中文逗号分隔。多个分隔符使用竖线 | 分隔
for (String s1 : split) {
s1 = s1.trim(); //去除前后空格
System.out.println("s1=" + s1);
}
// s1=楼栋1
// s1=楼栋2
// s1=楼栋3
// s1=楼栋4
// s1=楼栋5

字符串编码转换

1
2
3
4
5
6
7
public class Test {    
public static void main(String[] args) throws UnsupportedEncodingException {
String str = "捡田螺的小男孩";
String strIso = new String(str.getBytes("GB2312"), "ISO-8859-1");
System.out.println(strIso);
}
}

字符串中的连续空格替换为单个空格

1
2
3
String str = " abc  dd    ccc ";
str = str.replaceAll("\\s{2,}", " ").trim();
// abc dd ccc

小数转百分比

1
2
3
4
5
6
NumberFormat nt = NumberFormat.getPercentInstance();//获取格式化对象
nt.setMinimumFractionDigits(0);//设置百分数精确度2即保留两位小数
System.out.println("百分数1:" + nt.format(percent));//最后格式化并输出
// 0 - 0%
// 0.3 - 30%
// 1 - 100%

数字转字符串,位数不够补零

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
*
* @param number 数字
* @param digitsnumber 位数
* @return
*/
public static String getNumberString(int number, int digitsnumber) {
String num = String.valueOf(number);

if(num.length() >= digitsnumber) {
return num;
}

int prefix = digitsnumber-num.length();
for (int i = 0; i < prefix; i++) {
num = "0" + num;
}
return num;
}

数值运算

小数取整

1
2
3
4
5
6
7
8
9
10
11
12
//去掉小数保留整数
Math.floor(1.1) // 1.0
Math.floor(1.9) // 1.0
Math.floor(-2.6); //-3.0

//正数:四舍五入;负数:「五舍五入」
Math.round(1.4); //1
Math.round(1.5); //2
Math.round(-1.4); //-1
Math.round(-1.5); //-1
Math.round(-1.51); //-2
Math.round(-1.9); //-2

随机值

批量生成随机值

1
2
3
4
5
6
7
8
9
10
11
IntStream.range(0, 10).forEach(i-> System.out.println("i = " + i));
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9

整数值

1
2
3
4
5
6
7
8
// 0-20 随机整数
new Random().nextInt(20)

// 20-30 之间随机值
20 + new Random().nextInt(10)

// 20-30 之间随机值
String.format("%.0f", Math.random() * 10 + 20)

浮点数

1
2
3
4
5
6
7
8
9
10
11
12
//一、取 start - end 之间的小数,小数点后保留 1 位小数
//示例:20-30 之间的随机值,start=10, end=20
String format = String.format("%.1f", Math.random() * 10 + 20);

//二、取 0-1 之间的小数,小数点后保留 1 位小数
String.format("%.1f", new Random().nextFloat());

//三、取 0-10 之间的小数,小数点后保留 1 位小数
String.format("%.1f", new Random().nextFloat()*10);

//四、取 0-10 之间的小数,小数点后保留 1 位小数
String.format("%.1f", new Random().nextInt(100) * 0.1)

时间

超时时间点

1
2
// 30 分钟后的时间
Date date = new Date(System.currentTimeMillis() + 30 * 60 * 1000);

获取一天的开始和结束时间

1
2
3
4
5
6
7
8
Calendar calendar = new GregorianCalendar();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date dayStart = calendar.getTime();
calendar.add(Calendar.DATE, 1);
Date dayEnd = calendar.getTime();

判断是否在指定时间段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 /**
* 判断当前时间是否在指定时间段内
* @param start 时间段开始时间
* @param end 时间段结束时间
*/
public static boolean isBelong(String start, String end){
SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
Date now =null;
Date beginTime = null;
Date endTime = null;
try {
now = df.parse(df.format(new Date()));
beginTime = df.parse(start);
endTime = df.parse(end);
} catch (Exception e) {
e.printStackTrace();
}

return belongCalendar(now, beginTime, endTime);
}

/**
* 判断日期时间是否在指定日期时间段内
* @param nowTime
* @param beginTime
* @param endTime
* @return
*/
public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
Calendar date = Calendar.getInstance();
date.setTime(nowTime);

Calendar begin = Calendar.getInstance();
begin.setTime(beginTime);

Calendar end = Calendar.getInstance();
end.setTime(endTime);

if (date.after(begin) && date.before(end)) {
return true;
} else {
return false;
}
}

集合随机排序

1
2
// 随机排序
Collections.shuffle(examQuList);

数组

1
2
3
4
String[] arr = new String[] { token, timestamp, nonce };

// 将token、timestamp、nonce三个参数进行字典序排序
Arrays.sort(arr);

拼接字符串

String.join

语法

1
String.join(CharSequence delimiter, CharSequence... elements)

示例

1
2
3
4
String joined = String.join("/", "2014", "10", "28"); // "2014/10/28"

List<String> list = Arrays.asList("foo", "bar", "baz");
joined = String.join(";", list); // "foo;bar;baz"

StringJoiner

1
2
3
4
5
6
7
8
9
10
11
12
13
//字符串用 ,分割
StringJoiner joiner = new StringJoiner(",");
joiner.add("foo");
joiner.add("bar");
joiner.add("baz");
String joined = joiner.toString(); // "foo,bar,baz"

// add() calls can be chained
joined = new StringJoiner("-")
.add("foo")
.add("bar")
.add("baz")
.toString(); // "foo-bar-baz"

Collectors.joining

1
2
3
String joinedFirstNames = list.stream()
.map(Person::getFirstName)
.collect(Collectors.joining(",")); // "John, Anna, Paul"

String、Array、List 互转

Arrays.asList

1
2
3
4
5
6
7
8
List<Person> list = Arrays.asList(
new Person("John", "Smith"),
new Person("Anna", "Martinez"),
new Person("Paul", "Watson ")
);

String[] arr = new String[]{"hello", "world"};
List<String> list = Arrays.asList(arr);

string.split

split () 方法根据匹配给定的正则表达式来拆分字符串

注意: . $ |* 等转义字符,必须得加\\

注意:多个分隔符,可以用 | 作为连字符

语法

1
public String[] split(String regex, int limit)

参数

  • regex – 正则表达式分隔符。
  • limit – 分割的份数。

返回值

字符串数组

示例

1
String[] names = "张三|李四|王五|zhaoliu".split("\\|");

list.toArray()

1
2
3
4
5
6
7
8
9
String[] strArr = list.toArray(new String[list.size()]);

// 实例
List<String> l = new ArrayList<String>(){{
add("123");
add("456");
}};
String[] a = l.toArray(new String[2]);
System.out.println(a[1]); // 456

Double 类型转为 Integer

1
2
3
Double d = 13.5578;
int i = d.intValue();
System.out.println(i);

过滤特殊字符

1
2
3
4
5
6
7
8
9
/**
* 过滤特殊字符
* @param str
* @return
*/
public static String filterSpecialCharacters (String str){
String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
return Pattern.compile(regEx).matcher(str).replaceAll("").trim();
}

获取当前时间到第二天凌晨的毫秒数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* 获取当前时间到第二天凌晨的毫秒数
* @return
*/
public Long getSecondsNextEarlyMorning() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, 1);
// 改成这样就好了
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis() - System.currentTimeMillis();
}

页面中下载图片

html

1
<a href="url">下载图片</a>

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//http://localhost:8000/scm/event/20191114/471e2369a1794dec8c6cfa397934223e.jpg
String httpsrc = request.getParameter("httpsrc");

//文件名
String filename = httpsrc.substring(httpsrc.lastIndexOf("/")+1);
//文件后缀 jgp
String suffix = filename.substring(filename.indexOf(".")+1);
try {
URL httpurl = new URL(httpsrc);
BufferedImage image = ImageIO.read(httpurl);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, suffix, baos);
baos.flush();

response.setContentType("text/plain;charset=utf-8");//文本格式
if(request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){
//处理IE 的头部信息
response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,Charsets.UTF_8.toString()));
}else{
//处理其他的头部信息
response.setHeader("content-disposition", "attachment;filename="+filename);
}

//向客户端输入流下载
response.getOutputStream().write(baos.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}

抓取在线网页内容并解析-jsoup

参考

https://jsoup.org/download

Maven

1
2
3
4
5
6
<dependency>
<!-- jsoup HTML parser library @ https://jsoup.org/ -->
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.12.1</version>
</dependency>

使用

1
2
3
4
5
6
7
8
try {
Document doc = Jsoup.connect("http://www.tianqihoubao.com/aqi/nanyang.html").get();

Element content = doc.getElementById("today-quality");
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}

检查资源是否存在

1
2
3
4
5
6
7
8
9
10
11
12
13
// 判断资源是否存在
private boolean checkHttpResourceExists(String urlString) {
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("HEAD");
int responseCode = connection.getResponseCode();
return (responseCode >= 200 && responseCode < 400);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}

文件下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public void downloadNet(String url, String filePath) {
// 下载网络文件
int bytesum = 0;
int byteread = 0;

try {
URL fileUrl = new URL(url);
URLConnection conn = fileUrl.openConnection();
InputStream inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream(filePath);

byte[] buffer = new byte[1024];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

字符集过滤器

web.xml 配置

注意:过滤器配置为第一个

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- 配置字符集过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<!-- 配置项目的编码mapping -->
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

@PostConstruct

https://www.jianshu.com/p/98cf7d8b9ec3

  1. 从 Java EE5 规范开始,Servlet 中增加了两个影响 Servlet 生命周期的注解,@PostConstruct 和 @PreDestroy,这两个注解被用来修饰一个非静态的 void()方法

  2. 先 Constructor 再 @Autowired 后 @PostConstruct

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    public Class Tools {
        @Autowired
        private BusMapper busMapper;

        public Tools() {
            System.out.println ("此时 busMapper 方法未被注入: busMapper =" + busMapper);
        }

        @PostConstruct
        private void init() {
            System.out.println ("busMapper 方法已注入:" + busMapper);
        }
    }

UUID

  1. UUID是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的。通常平台会提供生成的API。按照开放软件基金会(OSF)制定的标准计算,用到了以太网卡地址纳秒级时间芯片ID码随机数

  2. java 生成 uuid

    1
    2
    3
    4
    5
    6
    UUID uuid = UUID.randomUUID();

    //ac90a107-e490-44e7-980d-22740e6daa99

    String uuidStr = uuid.toString().replace("-", "");
    //ac90a107e49044e7980d22740e6daa99

遍历 Map

  1. 遍历 key 和 value

    • Entryset

      1
      2
      3
      for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
      System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
      }
    • Iterator

      1
      2
      3
      4
      5
      6
      7
      8
      String key;
      Iterator<String> iterator = map.keySet().iterator();
      while (iterator.hasNext()) {
      key = iterator.next();
      String value = (String) map.get(key);

      System.out.println(key+":"+value);
      }
  2. 只需要 map 中的键或者值,可以通过 keySet 或 values 来实现遍历,而不是用 entrySet

    1
    2
    3
    for (Integer key : map.keySet()) {}

    for (Integer value : map.values()) {}

Map<Object, Object> 转 Map<String, String>

1
map.entrySet().stream().collect(Collectors.toMap(e -> (String)e.getKey(), e -> (String)e.getValue()));

Iterable 转 List或Set

1
2
3
4
5
Iterable<Law> iterable = lawService.getAll();

Set<String> result = StreamSupport.stream(iterable.spliterator(), false).map(Law::getName).collect(Collectors.toSet());

List<Law> result = StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList());