在Java开发中经常使用到一些比较常用的通用性代码,这里部分整理出来,记录一下零碎的知识代码,方便以后使用,以工具类形式给出;
//工具类对象: MyCommonUtil.java
package com.xx.yy.zz.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.util.StringUtils;
import org.springframework.util.FileCopyUtils;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
public class MyCommonUtil {
//判断是否为合法的电子邮件
public static boolean isEmailOk(String emailStr) {
try {
if (null == emailStr || emailStr.trim().isEmpty()) {
return false;
}
if (emailStr.indexOf("@") < 0) {
return false;
}
String regex = "^\\w+[\\w\\.-]+\\w+@\\w+([\\w\\-\\.])*\\.\\w{2,}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(emailStr.trim());
return matcher.find();
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
//通过spring框架的辅助类获取请求HttpServletRequest对象
public static HttpServletRequest getHttpServletRequest(){
return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
}
//通过spring框架的辅助类获取请求HttpServletResponse对象
public static HttpServletResponse getHttpServletResponse(){
return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
//return ((ServletWebRequest)RequestContextHolder.getRequestAttributes()).getResponse();
}
//通过spring框架从session里面获取对应项的值
public static Object(/XxxJavaBean) getObjectFromSession(String itemName){
if (null == itemName || itemName.trim().isEmpty()){
return null;
}
HttpSession session = RequestContextHolder.currentRequestAttributes().getSession();
return session.getAttribute(itemName.trim());
//return (XxxJavaBean)session.getAttribute(itemName.trim());
//或者
//ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
//return requestAttributes.getAttribute(itemName.trim(),RequestAttributes.SCOPE_SESSION);
//可根据需要修改方法的返回值类型,以及获取数据的类型转换
//return (XxxJavaBean)requestAttributes.getAttribute(itemName.trim(),RequestAttributes.SCOPE_SESSION);
}
//获取请求的头信息的Origin项信息
public static String getOrigin(){
HttpServletRequest request = getHttpServletRequest();
return request.getHeader("Origin");
}
//获取请求的头信息中名称为itemName项头信息
public static String getHeaderInfo(String itemName){
if (null == itemName || itemName.trim().isEmpty()){
return "";
}
HttpServletRequest request = getHttpServletRequest();
return request.getHeader(itemName.trim());
}
//获取请求的的IP地址
public static String getIpAddress(HttpServletRequest request){
String ip = null;
try{
ip = request.getHeader("x-forwarded-for");
if(StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("Proxy-Client-IP");
}
if(StringUtils.isEmpty(ip) || 0 == ip.length() || "unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("HTTP_CLIENT_IP");
}
if(StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if(StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)){
ip = request.getRemoteAddr();
}
} catch(Exception e){
e.printStackTrace();
}
return ip;
}
//通用从服务器以附件形式下载文件到客户端方法
public static void downloadFile(String svrFullPathName, String clientShowName,
HttpServletRequest req, HttpServletResponse res) throws Exception {
try {
Stirng dlFullName = (null == svrFullPathName ? "" : svrFullPathName.trim())
if (dlFullName.trim().isEmpty()) {
return;
}
File dlFile = new File(dlFullName);
if (null != dlFile && dlFile.exists() && dlFile.isFile()) {
FileInputStream fis = new FileInputStream(dlFile);
String fuffixName = svrFullPathName.substring(svrFullPathName.lastIndexOf("."));
if (null == clientShowName || clientShowName.trim().isEmpty()){
clientShowName = svrFullPathName.substring(svrFullPathName.lastIndexOf(File.separator)+1);
}
if (!clientShowName.toLowerCase().endsWith(fuffixName.toLowerCase())){
clientShowName = clientShowName + fuffixName;
}
//动态设置响应类型,根据文件类型设置
res.setContentType(req.getSession().getServletContext().getMimeType(fuffixName));
//设置响应头,attachment表示以附件形式下载,inline表示在线打开
res.setHeader("content-disposition","attachment;fileName=" + URLEncoder.encode(clientShowName,"UTF-8"));
ServletOutputStream os = res.getOutputStream();
FileCopyUtils.copy(fis,os);
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
//通用从服务器以在线打开形式下载文件到客户端方法
public static void downloadFile(String svrFullPathName, String clientShowName,
HttpServletRequest req, HttpServletResponse res) throws Exception {
try {
Stirng dlFullName = (null == svrFullPathName ? "" : svrFullPathName.trim())
if (dlFullName.trim().isEmpty()) {
return;
}
File dlFile = new File(dlFullName);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(dlFile));
byte[] buf = new byte[2048];
int len = 0;
response.reset();
URL url = new URL("file:///" + dlFullName);
response.setContentType(url.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename=" + dlFile.getName());
// 文件名应该编码成UTF-8
OutputStream out = response.getOutputStream();
while ((len = bis.read(buf)) > 0){
out.write(buf, 0, len);
}
bis.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
return;
}
}
//通用某文件以流式下载输出到客户端
public void downloadFile(HttpServletRequest req, HttpServletResponse res,
String dowloadFilePathAndName,String clientShowName) {
try {
if (null == dowloadFilePathAndName || dowloadFilePathAndName.trim().isEmpty()) {
return;
}
String dlFile = dowloadFilePathAndName.trim();
File checkFile = new File(dlFile);
if (!(checkFile.exists() && checkFile.isFile())) {
return;
}
int pos = dlFile.lastIndexOf(".");
String suffName = dlFile.substring(pos);
res.setContentType(req.getSession().getServletContext().getMimeType(suffName));
String showName = null;
if (null == clientShowName || clientShowName.trim().isEmpty()) {
showName = "DL" + Calendar.getInstance().getTime().getTime() + suffName;
} else {
showName = clientShowName.trim();
}
if (!suffName.equalsIgnoreCase(showName.substring(showName.lastIndexOf(".")))) {
showName = showName + suffName; //确保下载后缀名和文件的后缀名一样
}
FileInputStream fis = new FileInputStream(dlFile);
res.setHeader("content-disposition", "attachment;file="
+ URLEncoder.encode(showName, "UTF-8"));
ServletOutputStream os = res.getOutputStream();
FileCopyUtils.copy(fis, os);
} catch (Exception e) {
e.printStackTrace();
//logger.error("parameter dowloadFilePathAndName: {}", dowloadFilePathAndName);
//logger.error("parameter clientShowName: {}", clientShowName);
//logger.error("error info: {}", e);
}
}
//根据网络地址下载文件到本地
public void downloadNet(String fileNetUrl, String savePath, HttpServletResponse response)
throws Exception {
// 下载网络文件
try{
if (null == fileNetUrl || fileNetUrl.trim().isEmpty()) {
return;
}
int byteRead = 0;
URL url = new URL(fileNetUrl);
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
if (null == savePath || savePath.trim().isEmpty()) {
//如果保持路径为空,则保存在系统的临时文件中
savePath = System.getProperty("java.io.tmpdir")+File.separator;
}
File checkDir = new File(savePath)
if (!checkDir.exists() && !checkDir.isDirectory()){
checkDir.mkdir();
}
String suffixName = fileNetUrl.substring(fileNetUrl.lastIndexOf("."));
String fileName = "DL" + (new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date())) + suffixName;
fileName = savePath + fileName;
FileOutputStream fos = new FileOutputStream(fileName);
byte[] buffer = new byte[2408];;
while ((byteRead = inStream.read(buffer)) != -1) {
fs.write(buffer, 0, byteRead);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return;
}
//判断列表中元素内容是否是唯一的,true=列表元素唯一,false=不唯一,有重复
//注意:列表中元素为某Bean对象,判断对象是否一样时需重写/覆盖实现Bean的equals和hashCode方法
public static <T> boolean isUniqueList(List<T> refList) {
if (null == refList) {
return false;
}
Set<T> checkSet = new HashSet<T>();
checkSet.addAll(refList);
return (checkSet.size() == refList.size());
}
//返回一个去重的字符串类型元素的List列表
public static List<String> getUniqueItemList(List<String> list){
if (null == list || list.size() < 1) {
return list;
}
Set<String> tempSet = new HashSet<>();
for (String item:list) {
tempSet.add(item);
}
List<String> newList = new ArrayList<String>();
newList.addAll(tempSet);
return newList;
}
//返回一个去重的Long类型元素的List列表
public static List<Long> getUniqueItemList2(List<Long> list){
if (null == list || list.size() < 1) {
return list;
}
Set<Long> tempSet = new HashSet<>();
for (Long item:list) {
tempSet.add(item);
}
List<Long> newList = new ArrayList<Long>();
newList.addAll(tempSet);
return newList;
}
//返回一个去重的Integer类型元素的List列表
public static List<Integer> getUniqueItemList3(List<Integer> list){
if (null == list || list.size() < 1) {
return list;
}
Set<Integer> tempSet = new HashSet<>();
for (Integer item:list) {
tempSet.add(item);
}
List<Integer> newList = new ArrayList<Integer>();
newList.addAll(tempSet);
return newList;
}
//返回使用指定分割符连接列表各个元素的字符串
public static String concatListToStr(List<String> list, String splitor){
if (null == list || list.size() < 1) {
return null;
}
if (null == splitor || splitor.trim().isEmpty()) {
splitor = ",";
}
StringBuffer sb = new StringBuffer();
for (String item:list) {
if (null == item) {
continue;
}
sb.append(item).append(splitor);
}
String r = sb.toString();
return r.substring(0,r.length() - splitor.length());
}
//返回一个数组,该数组使用指定分隔符去分割输入的字符串
public static String[] toArray(String strList, String splitor){
if (null == strList || strList.trim().isEmpty()) {
return null;
}
if (null == splitor || splitor.trim().isEmpty()) {
splitor = ",";
}
return strList.split(splitor);
}
//返回一个列表,该list使用指定分隔符去分割输入的字符串
public static List<String> toList(String strList, String splitor){
if (null == strList || strList.trim().isEmpty()) {
return null;
}
if (null == splitor || splitor.trim().isEmpty()) {
splitor = ",";
}
String[] arr = strList.split(splitor);
return Arrays.asList(arr);
//或者
/*
List<String> r = new ArrayList<String>();
for (String item : arr) {
r.add(item);
}
return r;
*/
}
//将字符串类型的数组转变为列表
public static List<String> arrayToList(String[] array){
if (null == array || 0 == array.length) {
return null;
}
return Arrays.asList(array);
//或者
/*
List<String> r = new ArrayList<String>();
for (String item : array) {
r.add(item);
}
return r;
*/
}
//将字符串类型的列表转变为数组
public static String[] listToArray(List<String> list){
if (null == list || list.size() < 1) {
return null;
}
String[] r = new String[list.size()];
return list.toArray(r);
}
//...more code...
}
导入Excel操作,在项目中时常用到,下面以一个从客户端导入Excel的用户信息数据为例说明导入操作;
//1,定义相关model
package com.xx.yy.zz.model;
import java.io.Serializable;
public class User implements Serializable {
private String userName;
private String userCode;
private String password;
private String userEmail;
public User() {
super();
}
public User(String userName, String userCode, String password, String userEmail) {
super();
this.userName = userName;
this.userCode = userCode;
this.password = password;
this.userEmail = userEmail;
}
// ...getter/setter 省略
}
//2,项目引入操作Excel的jar依赖
/*
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
*/
//3,Excel导入操作的工具类,核心
package com.xx.yy.zz.util;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import com.xx.yy.zz.model.User;
/**
* @author shenzhenNBA
* @since 2020.05.24
*/
public class ImportExcelFromClient {
public ImportExcelFromClient() {
super();
}
//从Excel获取数据
public static Map<String, Object> importExcelFile(HttpServletRequest req,
MultipartFile upFile) throws Exception {
Map<String, Object> retMap = new HashMap<String, Object>();
retMap.put("code", "no");
retMap.put("msg", "导入数据失败");
retMap.put("data", null);
try {
if (null == upFile || upFile.getSize() < 1) {
return retMap;
}
String fileName = upFile.getOriginalFilename();
if (null == fileName || fileName.lastIndexOf(".") < 0) {
retMap.put("msg", "文件不合法");
return retMap;
}
String suffixName = fileName.substring(fileName.lastIndexOf("."));
if (!((".xls").equals(suffixName) || (".xlsx").equals(suffixName))) {
retMap.put("msg", "不是Excel文件");
return retMap;
}
String contentType = upFile.getContentType();
InputStream is = null;
Workbook wb = null;
Sheet sheet = null;
is = upFile.getInputStream();
if (fileName.toLowerCase().endsWith("xlsx")) {
wb = new XSSFWorkbook(is);
} else {
wb = new HSSFWorkbook(is);
}
sheet = wb.getSheet("MyExcelSheetName");
if (null == sheet) {
retMap.put("msg", "获取Excel的sheet对象为空");
return retMap;
}
List<User> users = null;
Map<String, Object> subRetMap = getUserFromExcel(sheet);
if ("ok".equalsIgnoreCase(subRetMap.get("code").toString())) {
users = (List<User>)subRetMap.get("data");
}
//more DB save operate...
retMap.put("code", "ok");
retMap.put("msg", "Excel导入数据成功");
retMap.put("data", null);
return retMap;
} catch (Exception e) {
e.printStackTrace();
return retMap;
}
}
//从Excel的校验表头和从各个行获取数据
public static Map<String, Object> getUserFromExcel(Sheet sheet) throws Exception {
Map<String, Object> retMap = new HashMap<String, Object>();
retMap.put("code", "no");
retMap.put("msg", "");
retMap.put("data", null);
String realHeads = "用户名,用户代码,用户密码,用户邮件";
try {
if (null == sheet) {
retMap.put("msg", "Excel的sheet为空");
return retMap;
}
//获取表头,约定Excel表头放在第一行,下标0开始
Row rowHead = sheet.getRow(0);
String strHeads = "";
String tempText = "";
Cell cell = null;
int i=0, maxSize=5; //Excel列数量根据实际情况而定
for (i=0; i<maxSize;i++) {
cell = rowHead.getCell(i);
if (null == cell) {
continue;
}
tempText = cell.getStringCellValue(); //获取字符型数据
//tempText = cell.getRichStringCellValue(); //获取富字符型数据
//tempText = cell.getNumericCellValue(); //获取数值型数据
//tempText = cell.getDateCellValue(); //获取日期型数据
if (i == maxSize - 1) {
strHeads = strHeads + tempText;
} else {
strHeads = strHeads + tempText + ",";
}
}
//此处可以进一步校验Excel表头的合法性
if (!strHeads.equalsIgnoreCase(realHeads)) {
retMap.put("msg", "Excel的标题不符合约定格式");
return retMap;
}
int lastRowNum = sheet.getLastRowNum();
int j = 1; //Excel数据从第二行开始(第一行为表头)
Row row = null;
String uName = "";
String uCode = "";
String uPwd = "";
String uEmail = "";
List<User> users = new ArrayList<User>();
for (j = 1; j < lastRowNum; j++) {
row = sheet.getRow(j);
if (null == row) {
continue;
}
uName = row.getCell(0).getStringCellValue();
uCode = row.getCell(1).getStringCellValue();
uPwd = row.getCell(2).getStringCellValue();
uEmail = row.getCell(3).getStringCellValue();
if (StringUtils.isEmpty(uName)
&& StringUtils.isEmpty(uCode)
&& StringUtils.isEmpty(uPwd)
&& StringUtils.isEmpty(uEmail)) {
continue; //如果正好数据都为空
}
User user = new User();
user.setUserName(uName);
user.setUserName(uCode);
user.setUserName(uPwd);
user.setUserName(uEmail);
users.add(user);
}
retMap.put("code", "ok");
retMap.put("msg", "获取Excel数据成功");
retMap.put("data", users);
return retMap;
} catch (Exception e) {
e.printStackTrace();
return retMap;
}
}
}
//4,controller层操作
package com.xx.yy.zz.controller;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.xx.yy.zz.util.ImportExcelFromClient;
/**
* @author shenzhenNBA
* @since 2020.05.24
*/
@Controller
@RequestMapping("/user")
public class ImportExcelFile {
@PostMapping(value="/import")
@ResponseBody
public String ImportExcelFileFromClient(HttpServletRequest req,
MultipartFile upFile) throws Exception {
Map<String, Object> retMap = ImportExcelFromClient.importExcelFile(req,upFile);
return retMap.get("msg").toString();
}
}
创建并向文件中写入内容
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
//向文件中写入内容
public boolean writeContent2File(String fileContent, String fullPathFile) throws IOException{
//return: true = success write content to file, false = not write
boolean retValue = false;
if(null == fileContent || fileContent.trim().isEmpty()
|| null == fullPathFile || fullPathFile.trim().isEmpty()){
return retValue;
}
String tempContent = fileContent.trim();
String pathFile = fullPathFile.trim();
File file = new File(pathFile);
if(!file.exists() || !file.isFile()){
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file,false);
//true = append to end,在原文末尾追加新内容;false=rewrite to file if exist,覆盖原来文件(如有)全新写入
OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
//按UTF-8编码写入文件内容
//FileWriter fw = new FileWriter(file,false);
//FileWriter(file,boolean append)后一个参数true=在原来文件后再增加新内容,false=覆盖原来内容,全新写入内容
try {
osw.write(tempContent);
osw.flush();
retValue = true;
} catch (Exception e) {
retValue = false;
}
tempContent = null;
pathFile = null;
file = null;
osw.close();
osw = null;
fos.close();
fos = null;
osw = null;
fos = null;
return retValue;
}
读取指定文件中的内容
import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;
//读取文件内容
public String readFileContent(String fullPathFile) throws IOException{
//return: "" or String content [no empty] of file
String retValue = "";
if(null == fullPathFile || fullPathFile.trim().isEmpty()){
return retValue;
}
String pathFile = fullPathFile.trim();
File file = new File(pathFile);
if(file.exists() && file.isFile()){
//字节码转成UTF-8码,返回字符串
InputStreamReader isr = new InputStreamReader(new FileInputStream(file),"UTF-8");
BufferedReader br = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String tempTxt = "";
while(null != (tempTxt = br.readLine())){
sb.append(tempTxt).append("\n");
}
retValue = sb.toString();
tempTxt = null;
sb = null;
br.close();
br = null;
isr = null;
}
pathFile = null;
file = null;
return retValue;
}
自定义线程池,以及使用方法
package com.xxx.yyy.kkk;
import java.io.Serializable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
* 配置异步任务线程池,然后注入springIOC容器,提供异步任务使用;
* @author shenzhenNBA
* @since 2022/01/15
*/
@Configuration
public class AsyncThreadPoolConfig implements Serializable {
private static final long serialVersionUID = 20220115010010L;
private static final int MAX_POOL_SIZE = 100;
private static final int CORE_POOL_SIZE = 20;
private static final String THREAD_NAME_PREFIX = "async_task_";
//创建线程池,并指定实例名称
@Bean("asyncTaskExecutor")
public AsyncTaskExecutor asyncTaskExecutor() {
ThreadPoolTaskExecutor asyncTaskExecutor = new ThreadPoolTaskExecutor();
asyncTaskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
asyncTaskExecutor.setCorePoolSize(CORE_POOL_SIZE);
asyncTaskExecutor.setThreadNamePrefix(THREAD_NAME_PREFIX);
asyncTaskExecutor.initialize();
return asyncTaskExecutor;
}
}
//线程池定义好之后的使用还有如下两个步骤
//使用线程池,在Service层某个类的某个方法指定异步执行,同时使用的自定义的异步线程池
@Async("asyncTaskExecutor")
public void updateProductReferNumListener(ProductEventSource pes){
//...todo...
}
//@EnableAsync启用异步功能,在Springboot的启动类中启用异步功能
//例如
@SpringBootApplication
@EnableDiscoveryClient
@MapperScan("com.xxx.yyy.kkk.dao")
@EnableAsync
public class WebApp {
public static void main(String[] args) {
SpringApplication.run(WebApp.class, args);
}
}
欢迎拍砖讨论...
版权声明:本文为shenzhenNBA原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。