Java 常用业务代码总结

本文最后更新于 2023年12月22日 下午

遍历文件夹下的所有文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static ArrayList<File> readFiles(File file){
ArrayList<File> list = new ArrayList<>();
File[] fs = file.listFiles();
assert fs != null;
for (File f : fs) {
// 若是目录,则递归读取
if (f.isDirectory()) {
readFiles(f);
}
// 若是文件,添加到集合
if (f.isFile()) {
list.add(f);
}
}
return list;
}

导出Excel

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
public void exportData(List<Map<String, Object>> data, Map<String, String> headerMap, String title, HttpServletResponse response) {
// 通过工具类创建writer,默认创建xls格式
ExcelWriter writer = ExcelUtil.getWriter();
writer.merge(headerMap.size() - 1, title);
for (Map<String, Object> stringObjectMap : data) {
List<String> removeKeys = new LinkedList<>();
for (String stringObjectKey : stringObjectMap.keySet()) {
if (!headerMap.containsKey(stringObjectKey)) {
removeKeys.add(stringObjectKey);
}
}
for (String removeKey : removeKeys) {
stringObjectMap.remove(removeKey);
}
}
writer.setHeaderAlias(headerMap);
// 一次性写出内容,使用默认样式,强制输出标题
writer.write(data, true);
int i = 0;
while (i < data.size()) {
//自动宽度
writer.autoSizeColumn(i);
i++;
}
//out为OutputStream,需要写出到的目标流
//response为HttpServletResponse对象
response.setContentType("application/vnd.ms-excel;charset=utf-8");
//devices.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
try {
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(title + ".xls", "utf-8"));
} catch (Exception e) {
e.printStackTrace();
}
ServletOutputStream out = null;
try {
out = response.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
writer.flush(out);
// 关闭writer,释放内存
writer.close();
//此处记得关闭输出Servlet流
IoUtil.close(out);
}

接口接收 Json 数组对象

1
2
3
@PostMapping("example")
public void example(@RequestBody List<exampleDto> exampleDtoList) {
}

接口通用返回泛型数据的格式

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
@ApiModel(value = "通用返回格式")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResultModel<T> implements Serializable {

private static final long serialVersionUID = 1L;

@ApiModelProperty(value = "返回状态码(0成功,-1失败)")
public int code;

@ApiModelProperty(value = "返回消息")
public String message;

@ApiModelProperty(value = "返回数据")
public T data;

public static<T> ResultModel<T> success() {
return new ResultModel<>(ResultEnums.SUCCESS.getCode(), ResultEnums.SUCCESS.getMessage(), null);
}


public static<T> ResultModel<T> success(T data) {
return new ResultModel<>(ResultEnums.SUCCESS.getCode(), ResultEnums.SUCCESS.getMessage(), data);
}


public static<T> ResultModel<T> success(T data, String message) {
return new ResultModel<>(ResultEnums.SUCCESS.getCode(), message, data);
}


public static<T> ResultModel<T> fail(String message) {
return new ResultModel<>(ResultEnums.FAIL.getCode(), message, null);
}


public static<T> ResultModel<T> fail(int code, String message) {
return new ResultModel<>(code, message, null);
}


public static<T> ResultModel<T> fail(int code, String message, T data) {
return new ResultModel<>(code, message, data);
}
}

开启定时任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.example.cron;

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@EnableScheduling
public class exampleCron {

/**
* 每天凌晨执行一次
*/
@Scheduled(cron = "1 * * * * ?")
public void example() {
}
}

开启事务

1
@Transactional(rollbackFor = Exception.class)

判断多个线程结束

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void threadIsOver(ArrayList<SearchByTime> threads, long start){
int size = threads.size();
HashSet<Object> died = new HashSet<>();
do {
for (SearchByTime thread : threads) {
if (!thread.isAlive()) {
died.add(thread.getId());
}
}
} while (size != died.size());
long end = System.currentTimeMillis();
System.out.println("\033[42m所有线程执行完毕" +
",线程数:"+ size +
",用时: " + (end - start) / 1000 + "s" + "\033[0m"
);
}
1
2
3
4
5
6
7
8
9
package com.example.thread;

public class SearchByTime extends Thread {

@Override
public void run() {
}
}

请求接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static JSONArray get(String apiFrom, String startTime, String endTime, String timeType) {
String baseUrl = "";
String url = baseUrl + apiFrom
+ "?start_time=" + startTime + "&"
+ "end_time=" + endTime + "&"
+ "time_type=" + timeType;
url = url.replaceAll(" ", "%20");
HttpResponse response = HttpRequest.get(url)
.header("charset", "UTF-8")
.timeout(60000 * 5)
.execute();
JSONObject jsonObject = JSONObject.parseObject(response.body());
Object code = jsonObject.get("code");
String msg = (String) jsonObject.get("msg");
JSONArray data = jsonObject.getJSONArray("result");
Integer successCode = 2000;
if (!successCode.equals(code)) {
logger.info(msg + "\n获取接口数据失败,接口地址:" + url);
return new JSONArray();
}
return data;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private JSONArray post(String token) {
JSONObject params = new JSONObject();
params.put("pageSize", 1000);
params.put("currentPage", currentPage);
HttpResponse response = HttpRequest.post(baseUrl + "xx")
.header("Content-Type", "application/json")
.header("charset", "UTF-8")
.header("Authorization", token)
.body(params.toJSONString())
.execute();

JSONObject JsonObject = JSONObject.parseObject(response.body());
Object code = JsonObject.get("code");
JSONArray data = JsonObject.getJSONArray("data");
if (!successCode.equals(code)) {
logger.info("获取接口数据失败");
}
return data;
}

文件上传下载

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Controller
public class FileController {

//@RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
//批量上传CommonsMultipartFile则为数组即可
@RequestMapping("/upload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {

//获取文件名 : file.getOriginalFilename();
String uploadFileName = file.getOriginalFilename();

//如果文件名为空,直接回到首页!
if ("".equals(uploadFileName)){
return "redirect:/index.jsp";
}
System.out.println("上传文件名 : "+uploadFileName);

//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
//如果路径不存在,创建一个
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件保存地址:"+realPath);

InputStream is = file.getInputStream(); //文件输入流
OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //文件输出流

//读取写出
int len=0;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
os.flush();
}
os.close();
is.close();
return "redirect:/index.jsp";
}

/*
* 采用file.Transto 来保存上传的文件
*/
@RequestMapping("/upload2")
public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
//上传文件地址
System.out.println("上传文件保存地址:"+realPath);

//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));

return "redirect:/index.jsp";
}

@RequestMapping(value="/download")
public String downloads(HttpServletResponse response , HttpServletRequest request) throws Exception{
//要下载的图片地址
String path = request.getServletContext().getRealPath("/static");
String fileName = "1.jpg";
System.out.println(path);
//1、设置response 响应头
response.reset(); //设置页面不缓存,清空buffer
response.setCharacterEncoding("UTF-8"); //字符编码
response.setContentType("multipart/form-data"); //二进制传输数据
//设置响应头
response.setHeader("Content-Disposition",
"attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));

File file = new File(path,fileName);
//2、 读取文件--输入流
InputStream input=new FileInputStream(file);
//3、 写出文件--输出流
OutputStream out = response.getOutputStream();

byte[] buff =new byte[1024];
int index=0;
//4、执行 写出操作
while((index= input.read(buff))!= -1){
out.write(buff, 0, index);
out.flush();
}
out.close();
input.close();
return null;
}
}

自动生成接口文档

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
/**
* Swagger2的接口配置
*
* @author loquy
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig
{
/**
* 创建API
*/
@Bean
public Docket createRestApi()
{
return new Docket(DocumentationType.SWAGGER_2)
// 详细定制
.apiInfo(apiInfo())
.select()
// 指定当前包路径
.apis(RequestHandlerSelectors.basePackage("com.example.app.api"))
// 扫描所有 .apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}

/**
* 添加摘要信息
*/
private ApiInfo apiInfo()
{
// 用ApiInfoBuilder进行定制
return new ApiInfoBuilder()
.title("标题")
.description("描述")
.version("版本号:1.01")
.build();
}
}

Bean 和 Map 的转换

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
package com.fjzxdz.ams.module.wryzl.utils;

import org.springframework.cglib.beans.BeanMap;

import java.util.HashMap;
import java.util.Map;

public class HashMapUtils {

public static int calculateInitialCapacity(int expectedSize) {
return (int) ((expectedSize / 0.75) + 1);
}

public static <T> Map<String, Object> beanToMap(T bean) {
Map<String, Object> map = new HashMap<>(16);
if (bean != null) {
BeanMap beanMap = BeanMap.create(bean);
for (Object key : beanMap.keySet()) {
map.put(key + "", beanMap.get(key));
}
}
return map;
}

public static <T> T mapToBean(Map<String, Object> map, Class<T> clazz) throws Exception {
T bean = clazz.newInstance();
BeanMap beanMap = BeanMap.create(bean);
beanMap.putAll(map);
return bean;
}
}

Oracle中分页查询语句

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
public HashMap<String, Object> getPageList(String listSql, String page, String pageSize) {
List<HashMap<String, Object>> list = simpleDao.getNativeQueryList("SELECT\n" +
"\t* \n" +
"FROM\n" +
"\t(\n" +
"SELECT\n" +
"\ta.*,\n" +
"\tROWNUM rn \n" +
"FROM\n" +
"\t(\n" + listSql +
"\t) a \n" +
"\t) \n" +
"WHERE\n" +
"\trn > ( " + page + " - 1 ) * " + pageSize + " \n" +
"\tAND rn <= ( " + page + " ) * " + pageSize + "");

List<HashMap<String, Object>> countList = simpleDao.getNativeQueryList("SELECT\n" +
"\tcount( * ) total\n" +
"FROM\n" +
"\t(\n" + listSql +
"\t)");

HashMap<String, Object> map = new HashMap<>(HashMapUtils.calculateInitialCapacity(4));
map.put("list", list);
map.put("total", countList.size() > 0 ? countList.get(0).get("total") : 0);
map.put("page", Integer.valueOf(page));
map.put("pageSize", Integer.valueOf(pageSize));

return map;
}

构造树形结构

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class TreeEntity {
private String uuid;
private String pid;
private List<TreeEntity> children;
private Object value;
private String name;

public TreeEntity(String pid, Object value, String name) {
this.uuid = UUID.randomUUID().toString();
this.pid = pid;
this.children = new ArrayList<>();
this.value = value;
this.name = name;
}

public String getUuid() {
return uuid;
}

public void setUuid(String uuid) {
this.uuid = uuid;
}

public String getPid() {
return pid;
}

public void setPid(String pid) {
this.pid = pid;
}

public List<TreeEntity> getChildren() {
return children;
}

public void setChildren(List<TreeEntity> children) {
this.children = children;
}

public Object getValue() {
return value;
}

public void setValue(Object value) {
this.value = value;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public void addChild(TreeEntity child) {
children.add(child);
}

public void removeChild(TreeEntity child) {
children.remove(child);
}
}

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
47
48
49
50

public static List<TreeEntity> buildTree(List<TreeEntity> nodes, boolean isSearch) {
if (isSearch) {
// 遍历节点,将uuid添加到nodeIds中
Set<String> nodeIds = new HashSet<>();
for (TreeEntity node : nodes) {
String nodeId = node.getUuid();
nodeIds.add(nodeId);
}

// 找到所有没有父节点的节点,并将它们的pid设置为null
for (TreeEntity node : nodes) {
String pid = node.getPid();
if (pid != null && !nodeIds.contains(pid)) {
node.setPid(null);
}
}
}

// 按照pid进行分组,然后递归构造树
Map<String, List<TreeEntity>> map = new HashMap<>();
for (TreeEntity node : nodes) {
String pid = node.getPid();
List<TreeEntity> group = map.computeIfAbsent(pid, k -> new ArrayList<>());
group.add(node);
}

List<TreeEntity> roots = map.get(null);
if (roots != null) {
for (TreeEntity root : roots) {
buildSubTree(root, map);
}
}

return roots;
}


private static void buildSubTree(TreeEntity node, Map<String, List<TreeEntity>> map) {
String nodeId = node.getUuid();
node.setValue(node.getUuid());
List<TreeEntity> children = map.get(nodeId);
node.setChildren(children);

if (children != null) {
for (TreeEntity child : children) {
buildSubTree(child, map);
}
}
}

读取目录的所有文件后逐行写入新的文件

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
* @author loquy
*/
public class ReadFiles {

public static void main(String[] args) {

File fileE = new File("H:\\test.txt");

if (fileE.exists()) {
boolean delete = fileE.delete();
System.out.println(delete);
}

File file = new File("H:\\");

File writerFile = new File("H:\\test.txt");
try {
boolean newFile = writerFile.createNewFile();
System.out.println(newFile);
} catch (IOException e) {
e.printStackTrace();
return;
}
readFiles(file, writerFile);
}

public static void readFiles(File file, File writerFile) {
File[] fs = file.listFiles();
assert fs != null;
for (File f : fs) {
// 若是目录,则递归读取
if (f.isDirectory()) {
readFiles(f, writerFile);
}
// 不是 java 后缀跳过
String suffix = f.getName().substring(f.getName().lastIndexOf(".") + 1);
if (!"java".equals(suffix)) {
continue;
}
if (f.isFile()) {
try {
readAndWriterFile(f, writerFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static void readAndWriterFile(File f, File writerFile) throws IOException {
BufferedReader br;
br = new BufferedReader(new FileReader(f.getPath()));
String con;
FileOutputStream fop = new FileOutputStream(writerFile, true);
OutputStreamWriter writer = new OutputStreamWriter(fop, StandardCharsets.UTF_8);
// 逐行读取
while ((con = br.readLine()) != null) {
// 跳过空行
if (!"".equals(con)) {
boolean is = false;
// 跳过tab
if (con.length() == 1) {
for (int i = 0; i < con.length(); i++) {
char c = con.charAt(i);
if ('\t' == c) {
is = true;
break;
}
}
}
if (!is) {
System.out.println(con);
writer.append(con);
writer.append("\n");
}
}
}
writer.close();
fop.close();
br.close();
}
}

常用字符串操作

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package com.example.demo.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.text.ParseException;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* The type Common String utils.
*
* @author loquy
*/
public class CommonStringUtils {

private static final String[] IS_DATE_PATTERNS = {
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd",
"yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm"
};

/**
* The constant IS_NUM_PATTERN.
*/
public static final Pattern IS_NUM_PATTERN = Pattern.compile("-?[0-9]+(\\.[0-9]+)?");

/**
* The constant MESSY_CODE_PATTERN.
*/
public static final Pattern MESSY_CODE_PATTERN = Pattern.compile("\\s*|\t*|\r*|\n*");

/**
* 解析字符串是否是日期
*
* @param string the string
* @return the date
*/
public static Date parseDate(String string) {
if (string == null) {
return null;
}
try {
return DateUtils.parseDate(string, IS_DATE_PATTERNS);
} catch (ParseException e) {
return null;
}
}

/**
* 解析字符串是否是数字
*
* @param str the str
* @return the boolean
*/
public static boolean isNumeric(String str) {
return IS_NUM_PATTERN.matcher(str).matches();
}

/**
* 获取指定长度随机数
*
* @param len the len
* @return the random
*/
public static String getRandom(int len) {
Random r = new Random();
StringBuilder rs = new StringBuilder();
for (int i = 0; i < len; i++) {
rs.append(r.nextInt(10));
}
return rs.toString();
}

/**
* 获取指定长度字符
*
* @param len the len
* @param character the character
* @return the characters
*/
public static String getCharacters(int len, String character) {
StringBuilder rs = new StringBuilder();
for (int i = 0; i < len; i++) {
rs.append(character);
}
return rs.toString();
}

/**
* 返回左移n位字符串方法
*
* @param str the str
* @param position the position
* @return the string
*/
public static String moveToLeft(String str, int position) {
String str1 = str.substring(position);
String str2 = str.substring(0, position);
return str1 + str2;
}

/**
* 返回右移n位字符串方法
*
* @param str the str
* @param position the position
* @return the string
*/
public static String moveToRight(String str, int position) {
String str1 = str.substring(str.length() - position);
String str2 = str.substring(0, str.length() - position);
return str1 + str2;
}

/**
* 检查字符串是否乱码
*
* @param strName the str name
* @return the boolean
*/
public static boolean isMessyCode(String strName) {
try {
Matcher m = MESSY_CODE_PATTERN.matcher(strName);
String after = m.replaceAll("");
String temp = after.replaceAll("\\p{P}", "");
char[] ch = temp.trim().toCharArray();

for (char c : ch) {
if (!Character.isLetterOrDigit(c)) {
String str = "" + c;
if (!str.matches("[\u4e00-\u9fa5]+")) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}

return false;
}

/**
* 原始数据里匹配关键字替换成别的字符串
*/
public static String keywordReplacement(String rawData, String keyword, String replacementString) throws Exception {
StringBuilder stringBuilder = new StringBuilder(rawData);

Matcher m = Pattern.compile(keyword).matcher(stringBuilder);
StringBuffer appendReplacement = new StringBuffer();
while (m.find()) {
m.appendReplacement(appendReplacement, replacementString);
}
if (StringUtils.isEmpty(appendReplacement)) {
throw new Exception("原始数据里没有匹配到关键字");
}
m.appendTail(appendReplacement);

return appendReplacement.toString();
}
}



Java 常用业务代码总结
http://www.loquy.cn/posts/3b0faab3.html
作者
loquy
发布于
2022年6月10日
更新于
2023年12月22日
许可协议