Utils
一、JsonUtils
1、依赖
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
2、code
public class JSONUtil {
private static Gson gson = null;
static{
gson = new Gson();//todo yyyy-MM-dd HH:mm:ss
}
public static synchronized Gson newInstance(){
if(gson == null){
gson = new Gson();
}
return gson;
}
//对象转json
public static String toJson(Object obj){
return gson.toJson(obj);
}
public static <T> T toBean(String json,Class<T> clz){
return gson.fromJson(json, clz);
}
public static <T> Map<String, T> toMap(String json, Class<T> clz){
Map<String, JsonObject> map = gson.fromJson(json, new TypeToken<Map<String,JsonObject>>(){}.getType());
Map<String, T> result = new HashMap<>();
for(String key:map.keySet()){
result.put(key,gson.fromJson(map.get(key),clz) );
}
return result;
}
public static Map<String, Object> toMap(String json){
Map<String, Object> map = gson.fromJson(json, new TypeToken<Map<String,Object>>(){}.getType());
return map;
}
public static <T> List<T> toList(String json, Class<T> clz){
JsonArray array = new JsonParser().parse(json).getAsJsonArray();
List<T> list = new ArrayList<>();
for(final JsonElement elem : array){
list.add(gson.fromJson(elem, clz));
}
return list;
}
}
二、加解密Utils
/**
* base64加密
* @param encoded
* @return
*/
public static String base64Encode(byte[] encoded) {
BASE64Encoder b64enc = new BASE64Encoder();
try
{
return b64enc.encode(encoded).replaceAll("\r\n", "").replaceAll("\n", "");
} catch (Exception e)
{
System.out.println(e);
return null;
}
}
/**
* base64解密
* @param reqdata
* @param charset
* @return
*/
public static String base64Decoder(String reqdata,String charset){
BASE64Decoder decoder=new BASE64Decoder();
try {
return new String(decoder.decodeBuffer(reqdata),charset);
} catch (Exception e) {
System.out.println(e);
return null;
}
}
public class MD5Util {
/***
* MD5加码 生成32位md5码
*/
public static String string2MD5(String inStr){
MessageDigest md5 = null;
try{
md5 = MessageDigest.getInstance("MD5");
}catch (Exception e){
//System.out.println(e.toString());
e.printStackTrace();
return "";
}
char[] charArray = inStr.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++){
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
/**
* 加密解密算法 执行一次加密,两次解密
*/
public static String convertMD5(String inStr){
char[] a = inStr.toCharArray();
for (int i = 0; i < a.length; i++){
a[i] = (char) (a[i] ^ 't');
}
String s = new String(a);
return s;
}
public static void main(String[] args) {
String name="nick";
String convert = convertMD5(name);
System.out.println("加密:"+convert);
String result = convertMD5(convert);
System.out.println("解密:"+result);
}
三、FileUtils
public class GetPropertiesUtile {
public static String getProperties(String filePath, String keyWord) throws IOException {
Properties properties = new Properties();
InputStream inputStream = GetPropertiesUtile.class.getResourceAsStream(filePath); // /properties/userInfo.properties
BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
properties.load(bf);
String value = properties.getProperty(keyWord);
return value;
}
public static void getJsonProperties(String filePath) throws IOException {
String userList = StreamUtils.copyToString(GetPropertiesUtile.class.getResourceAsStream(filePath),Charset.forName("UTF-8")); // /users.json
JSONArray accounts = JSONObject.parseArray(userList);
for (Object account:accounts){
String acc = ((JSONObject)account).get("account").toString();
String pwd = ((JSONObject)account).get("passwd").toString();
String pwdmd5 = DigestUtils.md5DigestAsHex(pwd.getBytes());
}
}
}
根据文件地址和路径下载
public static File downloadFile(String urlPath, String downloadDir) {
File file = null;
try {
// 统一资源
URL url = new URL(urlPath);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
//设置超时
httpURLConnection.setConnectTimeout(1000*5);
//设置请求方式,默认是GET
httpURLConnection.setRequestMethod("GET");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 打开到此 URL引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect();
// 文件大小
int fileLength = httpURLConnection.getContentLength();
// 控制台打印文件大小
logger.info("下载的资源大小为:{}",FormetFileSize(fileLength)+"M");
// 建立链接从请求中获取数据
URLConnection con = url.openConnection();
BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
// 指定文件名称(有需求可以自定义)
String fileFullName="";
if(urlPath.contains("=")){
fileFullName=urlPath.substring(urlPath.lastIndexOf("=")+1);
}
// 指定存放位置(有需求可以自定义)
String path = downloadDir + File.separatorChar + fileFullName;
file = new File(path);
// 校验文件夹目录是否存在,不存在就创建一个目录
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(file);
int size = 0;
int len = 0;
byte[] buf = new byte[1024];
while ((size = bin.read(buf)) != -1) {
len += size;
out.write(buf, 0, size);
}
// 关闭资源
bin.close();
out.close();
logger.info("文件下载成功");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
logger.info("文件下载失败");
} finally {
return file;
}
}
private static double FormetFileSize(long fileS) {
DecimalFormat df = new DecimalFormat("#.00");
double fileSizeLong = 0;
fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576));
return fileSizeLong;
}
根据文件地址和路径上传
public static String uploadFile(String url, File file) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse httpResponse = null;
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).build();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
httpPost.setHeader("token","fdab436e-00b4-4ba3-a343-6995f40e0e97");
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
//multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
//File file = new File("F:\\Ken\\1.PNG");
//FileBody bin = new FileBody(file);
//multipartEntityBuilder.addBinaryBody("file", file,ContentType.create("image/png"),"abc.pdf");
//当设置了setSocketTimeout参数后,以下代码上传PDF不能成功,将setSocketTimeout参数去掉后此可以上传成功。上传图片则没有个限制
//multipartEntityBuilder.addBinaryBody("file",file,ContentType.create("application/octet-stream"),"abd.pdf");
multipartEntityBuilder.addBinaryBody("file", file);
//multipartEntityBuilder.addPart("comment", new StringBody("This is comment", ContentType.TEXT_PLAIN));
multipartEntityBuilder.addTextBody("comment", "this is comment");
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
httpResponse = httpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200) {
Map<String, String> kv = new HashMap<>();
kv.put("files", "");
Map<String, String> stringStringMap = convertResponse(httpResponse, kv);
String value = kv.get("files");
JSONObject result=JSON.parseObject(value);
String receipt = result.getString("file");
//result
// BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
// StringBuffer buffer = new StringBuffer();
// String str = "";
// whil
// e (!StringUtils.isEmpty(str = reader.readLine())) {
// buffer.append(str);
// }
// System.out.println(buffer.toString());
return receipt;
}
httpClient.close();
if (httpResponse != null) {
httpResponse.close();
}
return null;
}
bytetofile
public static File byte2File(byte[] buf, String filePath, String fileName){
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try{
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()){
dir.mkdirs();
}
file = new File(filePath + File.separator + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(buf);
}catch (Exception e){
e.printStackTrace();
}
finally{
if (bos != null){
try{
bos.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (fos != null){
try{
fos.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
return file;
}
world模板替换文本生成特定文件
//tmpFile:模板路径 ,map:替换参数, export:生成文件路径
//FileLoadUtil.getBuild("static/temper.doc", map,exportFilePath);
public static String getBuild(String tmpFile, Map<String, String> contentMap,String exportFilePath){
InputStream inputStream = FileLoadUtil.class.getClassLoader().getResourceAsStream(tmpFile);
HWPFDocument document = null;
try {
document = new HWPFDocument(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
// 读取文本内容
Range bodyRange = document.getRange();
// 替换内容
for (Map.Entry<String, String> entry : contentMap.entrySet()) {
bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue());
}
//导出到文件
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
document.write(byteArrayOutputStream);
byte[] bytes = byteArrayOutputStream.toByteArray();
OutputStream outputStream = new FileOutputStream(exportFilePath);
outputStream.write(bytes);
outputStream.close();
return exportFilePath;
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
四、PDFUtil
public class NxtPDFUtil {
private static final Logger logger = LoggerFactory.getLogger(NxtPDFUtil.class);
/***
* PDF文件转PNG图片,全部页数
*
* @param PdfFilePath pdf完整路径
* @param dpi dpi越大转换后越清晰,相对转换速度越慢
* @return
*/
public static String pdf2Image(String PdfFilePath, int dpi, String imgPDFPath) {
File file = new File(PdfFilePath);
PDDocument pdDocument;
try {
// String imgPDFPath = file.getParent();
int dot = file.getName().lastIndexOf('.');
String imagePDFName = file.getName().substring(0, dot);
// 获取图片文件名
pdDocument = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(pdDocument);
/* dpi越大转换后越清晰,相对转换速度越慢 */
PdfReader reader = new PdfReader(PdfFilePath);
int pages = reader.getNumberOfPages();
StringBuffer imgFilePath = null;
imgFilePath = new StringBuffer();
imgFilePath.append(imagePDFName);
imgFilePath.append("_");
imgFilePath.append("img");
imgFilePath.append(".png");
BufferedImage image = null;
try {
image = renderer.renderImageWithDPI(0, dpi);
} catch (EOFException e) {
logger.error(e.getMessage());
}
String path = imgPDFPath + File.separator + imgFilePath.toString();
OutputStream ops = new FileOutputStream(new File(path));
ImageIO.write(image, "png", ops);
logger.info("PDF文档转PNG图片成功!");
return imgFilePath.toString();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("转化失败");
}
}
}
五、文件上传接口定义
private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);
@Value("${common.fileupload.file.savepath}")
private String fileSavePath;
/**
* Upload the File to the specified folder(configured in properties file) , modify the file name
*
* @param multipartFile
* @return
* @throws IOException
*/
@PostMapping("/file/upload")
@ResponseBody
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile multipartFile) throws IOException {
Assert.notNull(multipartFile, "Param multipartFile can't be null. Please check the request params.");
logger.info(String.format("The original file name uploaded is=[%s]" , multipartFile.getOriginalFilename()));
String newFileName = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(multipartFile.getOriginalFilename());
multipartFile.transferTo(new File(fileSavePath + newFileName));
return ResponseEntity.ok(newFileName);
}
六、日期比较
public class DateUtil {
public static int compareDate(String DATE1, String DATE2) {
return compareDateFormat(DATE1,DATE2,"yyyy-MM-dd HH:mm:ss");
}
public static int compareDate(String DATE) throws ParseException {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date dt1 = df.parse(DATE);
Date dt2 =new Date();
return judgeDate(dt1,dt2);
}
public static int compareDateFormat(String DATE1, String DATE2,String format) {
//DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
SimpleDateFormat df = new SimpleDateFormat(format);
try {
Date dt1 = df.parse(DATE1);
Date dt2 = df.parse(DATE2);
return judgeDate(dt1,dt2);
} catch (Exception exception) {
exception.printStackTrace();
}
return 0;
}
public static String getNowDateString(){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
return df.format(new Date());
}
public static int judgeDate(Date dt1, Date dt2){
if (dt1.getTime() > dt2.getTime()) {
//"dt1 在dt2前"
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
//dt1在dt2后
return -1;
} else {
return 0;
}
}
}
七、读取excel
public class ExcelUtil {
/**
*
* @Title: readXls
* @Description: 处理xls文件
* @param @param path
* @param @return
* @param @throws Exception 设定文件
* @return List<List<String>> 返回类型
* @throws
*
*
* 1.先用InputStream获取excel文件的io流
* 2.然后穿件一个内存中的excel文件HSSFWorkbook类型对象,这个对象表示了整个excel文件。
* 3.对这个excel文件的每页做循环处理
* 4.对每页中每行做循环处理
* 5.对每行中的每个单元格做处理,获取这个单元格的值
* 6.把这行的结果添加到一个List数组中
* 7.把每行的结果添加到最后的总结果中
* 8.解析完以后就获取了一个List<List<String>>类型的对象了
*
*/
private List<List<String>> readXls(String path) throws Exception {
InputStream is = new FileInputStream(path);
// HSSFWorkbook 标识整个excel
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
List<List<String>> result = new ArrayList<List<String>>();
int size = hssfWorkbook.getNumberOfSheets();
// 循环每一页,并处理当前循环页
for (int numSheet = 0; numSheet < size; numSheet++) {
// HSSFSheet 标识某一页
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
// 处理当前页,循环读取每一行
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
// HSSFRow表示行
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
int minColIx = hssfRow.getFirstCellNum();
int maxColIx = hssfRow.getLastCellNum();
List<String> rowList = new ArrayList<String>();
// 遍历改行,获取处理每个cell元素
for (int colIx = minColIx; colIx < maxColIx; colIx++) {
// HSSFCell 表示单元格
HSSFCell cell = hssfRow.getCell(colIx);
if (cell == null) {
continue;
}
rowList.add(getStringVal(cell));
}
result.add(rowList);
}
}
return result;
}
// 存在的问题
/*
* 其实有时候我们希望得到的数据就是excel中的数据,可是最后发现结果不理想
* 如果你的excel中的数据是数字,你会发现Java中对应的变成了科学计数法。
* 所以在获取值的时候就要做一些特殊处理来保证得到自己想要的结果
* 网上的做法是对于数值型的数据格式化,获取自己想要的结果。
* 下面提供另外一种方法,在此之前,我们先看一下poi中对于toString()方法:
*
* 该方法是poi的方法,从源码中我们可以发现,该处理流程是:
* 1.获取单元格的类型
* 2.根据类型格式化数据并输出。这样就产生了很多不是我们想要的
* 故对这个方法做一个改造。
*/
/*public String toString(){
switch(getCellType()){
case CELL_TYPE_BLANK:
return "";
case CELL_TYPE_BOOLEAN:
return getBooleanCellValue() ? "TRUE" : "FALSE";
case CELL_TYPE_ERROR:
return ErrorEval.getText(getErrorCellValue());
case CELL_TYPE_FORMULA:
return getCellFormula();
case CELL_TYPE_NUMERIC:
if(DateUtil.isCellDateFormatted(this)){
DateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy")
return sdf.format(getDateCellValue());
}
return getNumericCellValue() + "";
case CELL_TYPE_STRING:
return getRichStringCellValue().toString();
default :
return "Unknown Cell Type:" + getCellType();
}
}*/
/**
* 改造poi默认的toString()方法如下
* @Title: getStringVal
* @Description: 1.对于不熟悉的类型,或者为空则返回""控制串
* 2.如果是数字,则修改单元格类型为String,然后返回String,这样就保证数字不被格式化了
* @param @param cell
* @param @return 设定文件
* @return String 返回类型
* @throws
*/
public static String getStringVal(HSSFCell cell) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
return cell.getBooleanCellValue() ? "TRUE" : "FALSE";
case Cell.CELL_TYPE_FORMULA:
return cell.getCellFormula();
case Cell.CELL_TYPE_NUMERIC:
cell.setCellType(Cell.CELL_TYPE_STRING);
return cell.getStringCellValue();
case Cell.CELL_TYPE_STRING:
return cell.getStringCellValue();
default:
return "";
}
}
}