合并两个JSONArray
//合并两个JSONArray
public static JSONArray joinJSONArray(JSONArray mData, JSONArray array) {
StringBuffer buffer = new StringBuffer();
try {
int len = mData.length();
for (int i = 0; i < len; i++) {
JSONObject obj1 = (JSONObject) mData.get(i);
if (i == len - 1)
buffer.append(obj1.toString());
else
buffer.append(obj1.toString()).append(",");
}
len = array.length();
if (len > 0)
buffer.append(",");
for (int i = 0; i < len; i++) {
JSONObject obj1 = (JSONObject) array.get(i);
if (i == len - 1)
buffer.append(obj1.toString());
else
buffer.append(obj1.toString()).append(",");
}
buffer.insert(0, "[").append("]");
return new JSONArray(buffer.toString());
} catch (Exception e) {
}
return null;
}
逗号分割的字符串去重
public static StringBuilder checkStr(StringBuilder sb) {
String stri = sb.toString();
String[] strArray = null;
strArray = stri.split(","); //拆分字符为"," ,然后把结果交给数组strArray
Set<String> set = new HashSet<>();
for(int i=0;i<strArray.length;i++){
set.add(strArray[i]);
}
String[] arrayResult = (String[]) set.toArray(new String[set.size()]);
StringBuilder sb1 = new StringBuilder();
for(int i = 0; i < arrayResult.length; i++){
if(!StringHelper.isNullOrEmpty(arrayResult[i])){
sb1. append(arrayResult[i] + ",");
}
}
return sb1;
}
压缩文件
package com.jl.syoa.srv.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.log4j.Logger;
public class ZipUtil {
public static Logger log = Logger.getLogger(ZipUtil.class);
/**
* 压缩文件
* @param srcFiles 待压缩文件
* @param zipFile 压缩后文件
*/
public static void zipFiles(List<File> srcFiles, File zipFile) throws Exception{
byte[] buff = new byte[1024];
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(fos);
for (int i = 0; i < srcFiles.size(); i++) {
FileInputStream fis = new FileInputStream(srcFiles.get(i));
zos.putNextEntry(new ZipEntry(srcFiles.get(i).getName()));
int len;
while((len = fis.read(buff)) > 0){
zos.write(buff, 0, len);
}
zos.closeEntry();
fis.close();
}
} catch (Exception e) {
log.error("创建压缩文件异常", e);
} finally {
if(zos != null){
zos.close();
}
if(fos != null){
fos.close();
}
}
}
}
StringUtil
package com.jl.syoa.srv.util;
import java.util.List;
public class StringUtil {
/**
* 字符串是否为空
* @param str 字符串
* @return boolean
*/
public static boolean isNull(String str){
if(str != null && str.length() > 0){
return false;
}else{
return true;
}
}
/**
* 字符串是否不为空
* @param str 字符串
* @return boolean
*/
public static boolean isNotNull(String str){
if(str != null && str.length() > 0){
return true;
}else{
return false;
}
}
/**
* 将字符串以特殊字符拼接
* @param strs 字符串集合
* @param symbol 特殊字符
* @return String
*/
public static String conListToStr(List<String> strs,String symbol){
if(strs != null && strs.size() > 0 && symbol != null){
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < strs.size(); i++) {
buffer.append(strs.get(i)).append(symbol);
}
String nowStr = buffer.toString();
String rtnStr = nowStr.substring(0, nowStr.length()-symbol.length());
return rtnStr;
}else{
return "";
}
}
}
SFTP
package com.jl.syoa.srv.util.sftp;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import com.jl.syoa.srv.util.sftp.bean.FileUpload;
import org.apache.log4j.Logger;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
/**
* sftp工具类
* @author ShenHaijun
*
*/
public class SFTPUtil {
public static Logger log = Logger.getLogger(SFTPUtil.class);
/**
* 上传文件
* @param localDir 本地目录
* @param remoteDir 远程目录
* @param filename 文件名称
* @param timeout 超时时间
* @return TRUE:上传完成 FALSE:上传失败
*/
public static boolean uploadFile(String localDir, String remoteDir, String filename, int timeout){
boolean isFinished = false;
try {
//获取连接
SFTPChannel channel = new SFTPChannel();
ChannelSftp chSftp = channel.getChanel(timeout);
//上传
SFTPProgress progress = new SFTPProgress();//上传进度
String remoteFilename = remoteDir + filename + ".tmp";//上传过程中临时文件名
chSftp.put(localDir + filename, remoteFilename, progress);//上传
isFinished = progress.isEnd();//是否已经上传完成
if(isFinished){
chSftp.rename(remoteFilename, remoteDir + filename);//上传完成重命名
}
//关闭连接
chSftp.quit();
channel.closeChannel();
} catch (Exception e) {
log.error("sftp上传文件失败", e);
isFinished = false;
}
return isFinished;
}
/**
* 上传文件
* @param fileUploads 批量上传的文件bean
* @param timeout 超时时间
* @return list 上传失败的文件名称
*/
public static List<String> uploadFiles(FileUpload[] fileUploads, int timeout){
List<String> list = new ArrayList<String>() ;
boolean isFinished = false;
try {
//获取连接
SFTPChannelForPushOA channel = new SFTPChannelForPushOA();
ChannelSftp chSftp = channel.getChanel(timeout);
//上传
SFTPProgress progress = new SFTPProgress();//上传进度
for(FileUpload file : fileUploads){
String remoteFilename = file.remoteDir + file.filename;
try{
chSftp.put(file.localDir, remoteFilename, progress);//上传
}catch(Exception e){
list.add(file.filename);
log.error("文件:"+file.localDir+" 上传失败",e);
}
isFinished = progress.isEnd();//是否已经上传完成
}
//关闭连接
chSftp.quit();
channel.closeChannel();
} catch (Exception e) {
log.error("sftp上传文件失败", e);
isFinished = false;
}
return list;
}
/**
* 下载文件
* @param localDir 本地目录
* @param remoteDir 远程目录
* @param filename 文件名称
* @param timeout 超时时间
* @return TRUE:下载完成 FALSE:下载失败
*/
public static boolean downloadFile(String localDir, String remoteDir, String filename, int timeout){
boolean isFinished = false;
try {
//获取连接
SFTPChannel channel = new SFTPChannel();
ChannelSftp chSftp = channel.getChanel(timeout);
//下载
SFTPProgress progress = new SFTPProgress();//下载进度
chSftp.get(remoteDir + filename, localDir, progress);//下载
isFinished = progress.isEnd();//是否已经下载完成
//关闭连接
chSftp.quit();
channel.closeChannel();
} catch (Exception e) {
log.error("sftp下载文件失败", e);
isFinished = false;
}
return isFinished;
}
/**
* 判断远程服务器上目录下某个文件是否存在
* @param remoteDir 远程目录
* @param filename 文件名称
* @param timeout 连接超时时间
* @return boolean True:存在,False:不存在
*/
public static boolean isFileExist(String remoteDir, String filename, int timeout){
boolean isExist = false;
try {
//获取连接
SFTPChannel channel = new SFTPChannel();
ChannelSftp chSftp = channel.getChanel(timeout);
//判断该文件是否存在
Vector<LsEntry> lsEntrys = chSftp.ls(remoteDir);
if(lsEntrys != null && lsEntrys.size() > 0){
for (int i = 0; i < lsEntrys.size(); i++) {
String name = lsEntrys.get(i).getFilename();
if(name != null && name.equals(filename)){
isExist = true;
}
}
}
//关闭连接
chSftp.quit();
channel.closeChannel();
} catch (Exception e) {
log.error("sftp判断文件是否存在异常...", e);
isExist = false;
}
return isExist;
}
}
短信
package com.jl.syoa.srv;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SendMessageUtils {
private static final Logger logger = LoggerFactory.getLogger(SendMessageUtils.class);
private static final String MSGURL = "http://localhost:8080/SendMessageCenter/SendSms";
private static String getPhoneStr(List<String> phoneList){
String str = "";
int count = 1;
for(String phone : phoneList){
str = str + phone;
if(phoneList.size() > 1 && phoneList.size() != count){
str = str + ",";
}
count ++;
}
return str;
}
public static void sendMessage(String msg, List<String> phoneList) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("msg", msg);
params.put("phoneList", getPhoneStr(phoneList));
sendPost(MSGURL, params);
}
/**
* 使用URLConnection发送post
*
*/
public static String sendPost(String url, Map<String, Object> params) {
StringBuilder resultBuffer = null;
// 构建请求参数
StringBuilder sbParams = new StringBuilder();
if (params != null && params.size() > 0) {
for (Entry<String, Object> e : params.entrySet()) {
sbParams.append(e.getKey());
sbParams.append("=");
sbParams.append(e.getValue());
sbParams.append("&");
}
}
URLConnection con = null;
OutputStreamWriter osw = null;
BufferedReader br = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
con = realUrl.openConnection();
// 设置通用的请求属性
con.setRequestProperty("accept", "*/*");
con.setRequestProperty("connection", "Keep-Alive");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
con.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
con.setDoOutput(true);
con.setDoInput(true);
// 获取URLConnection对象对应的输出流
osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
if (sbParams != null && sbParams.length() > 0) {
// 发送请求参数
osw.write(sbParams.substring(0, sbParams.length() - 1));
// flush输出流的缓冲
osw.flush();
}
// 定义BufferedReader输入流来读取URL的响应
resultBuffer = new StringBuilder();
int contentLength = Integer.parseInt(con
.getHeaderField("Content-Length"));
if (contentLength > 0) {
br = new BufferedReader(new InputStreamReader(
con.getInputStream(), "UTF-8"));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
osw = null;
throw new RuntimeException(e);
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
}
}
}
return resultBuffer.toString();
}
}
读取文件
package com.jl.syoa.srv.util.sftp;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
/**
* 读文件工具类
* @author ShenHaijun
*
*/
public class ReadFileUtil {
public static Logger log = Logger.getLogger(ReadFileUtil.class);
/**
* 按行读取文件
* @param fileSrc 文件路径
* @return 读取结果
*/
public static List<String> readByLine(String fileSrc){
List<String> rtnStrs = new ArrayList<String>();
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(fileSrc);
br = new BufferedReader(fr);
//按行读取文件
String str = null;
while((str = br.readLine()) != null){
rtnStrs.add(str);
}
} catch (Exception e) {
log.error("按行读取文件异常", e);
} finally {
//关流
try {
if(br != null){
br.close();
}
} catch (Exception e2) {
log.error("关闭BufferedReader异常", e2);
}
try {
if(fr != null){
fr.close();
}
} catch (Exception e2) {
log.error("关闭FileReader异常", e2);
}
}
return rtnStrs;
}
/**
* 读取文件中有多少行
* @param fileSrc 文件路径
* @return int
*/
public static int readLineNum(String fileSrc){
int lineNum = 0;
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(fileSrc);
br = new BufferedReader(fr);
//按行读取文件
while(br.readLine() != null){
lineNum++;
}
} catch (Exception e) {
log.error("按行读取文件异常", e);
} finally {
//关流
try {
if(br != null){
br.close();
}
} catch (Exception e2) {
log.error("关闭BufferedReader异常", e2);
}
try {
if(fr != null){
fr.close();
}
} catch (Exception e2) {
log.error("关闭FileReader异常", e2);
}
}
return lineNum;
}
}
office
package com.jl.syoa.srv.util;
import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.net.ConnectException;
import java.nio.channels.FileChannel;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.ibizsys.paas.util.StringHelper;
import org.apache.log4j.Logger;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.jl.syoa.srv.mail.CommonUtil;
public class OfficeUtil {
public static final String lineBreak = "\r\n";
public static final String lineBreakN = "\n";
public static Logger log = Logger.getLogger(OfficeUtil.class);
public static final String UTF8 = "UTF-8";
public static final String comma = ",";
public static final String verticalLine = "|";
/**
* office类型转换
*
* @param sourceFile
* 转换源文件
* @param targetFile
* 转换目标文件
* @return 转换目标文件
* @throws Exception
*/
public static File convert(String sourceFile, String targetFile) throws Exception {
File target;
// 创建Openoffice连接
OpenOfficeConnection con = new SocketOpenOfficeConnection(8100);
try {
// 连接
log.info("======================================================================连接开始时间:"+CommonUtil.getNowDateStr());
con.connect();
log.info("======================================================================连接结束时间:"+CommonUtil.getNowDateStr());
// 创建转换器
DocumentConverter converter = new OpenOfficeDocumentConverter(con);
target = new File(targetFile);
// 转换文档问html
log.info("=======================================================================转换开始时间:"+CommonUtil.getNowDateStr());
converter.convert(new File(sourceFile), target);
log.info("=======================================================================转换结束时间:"+CommonUtil.getNowDateStr());
return target;
} catch (ConnectException e) {
throw new Exception("获取OpenOffice连接失败");
} finally {
// 关闭openoffice连接
log.info("========================================================================关闭连接开始时间:"+CommonUtil.getNowDateStr());
con.disconnect();
log.info("========================================================================关闭连接结束时间:"+CommonUtil.getNowDateStr());
}
}
/**
* @param filePathAndName
* word源文件
* @param tempFilePathAndName
* 临时文件
* @param isDelete
* 是否删除临时文件
* @return
* @throws Exception
*/
public static String getHtmlStringFromWord(String filePathAndName, String tempFilePathAndName,
Boolean isDelete) throws Exception {
File tempFile = null;
try {
tempFile = convert(filePathAndName, tempFilePathAndName);
return clearFormat(getFileContentString(tempFilePathAndName, UTF8), filePathAndName);
} finally {
if (isDelete) {
tempFile.delete();
}
}
}
/**
* @param filePathAndName
* word源文件
* @param tempFilePathAndName
* 临时文件
* @param isDelete
* 是否删除临时文件
* @return
* @throws Exception
*/
public static String getTxtStringFromWord(String filePathAndName, String tempFilePathAndName,
Boolean isDelete) throws Exception {
File tempFile = null;
try {
tempFile = convert(filePathAndName, tempFilePathAndName);
return getFileContentString(tempFilePathAndName, UTF8);
} finally {
if (isDelete) {
tempFile.delete();
}
}
}
/**
* 读取文件内容
*
* @param filePathAndName
* @param decode
* @return
*/
public static String getFileContentString(String filePathAndName, String decode) {
InputStreamReader read = null;
BufferedReader bufferedReader = null;
StringBuilder contents = new StringBuilder();
try {
File file = new File(filePathAndName);
if (!file.exists()) {
return null;
}
read = new InputStreamReader(new FileInputStream(file), decode);
bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
contents.append(lineTxt);
contents.append(lineBreak);
}
System.out.println(contents.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (read != null) {
try {
read.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return contents.toString();
}
/**
* 清除一些不需要的html标记
*
* @param htmlStr
* 带有复杂html标记的html语句
* @return 去除了不需要html标记的语句
*/
protected static String clearFormat(String htmlStr, String pathString) {
String path = pathString.substring(0, pathString.lastIndexOf("/") + 1);
htmlStr = htmlStr.replace("IMG SRC=\"", "IMG SRC=\"" + path).replace(
"#cce8cf", "#ffffff");
return htmlStr;
}
public static void replaceBookmark(String sourceFile, String targetFile,
Map<String, String> content) throws IOException {
String tmpsourceFile = sourceFile.replace(".docx", "_tmp.docx");
nioTransferCopy(sourceFile, tmpsourceFile);
XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(tmpsourceFile));
BookMarks bookMarks = new BookMarks(document);
// 循环进行替换
Iterator<String> bookMarkIter = bookMarks.getNameIterator();
while (bookMarkIter.hasNext()) {
String bookMarkName = bookMarkIter.next();
System.out.println(bookMarkName);
// 得到标签名称
BookMark bookMark = bookMarks.getBookmark(bookMarkName);
// 进行替换
if (content.get(bookMarkName) != null) {
if("qfr".equals(bookMarkName)){
bookMark.insertTextAtBookMark(content.get(bookMarkName), BookMark.REPLACE,"楷体");
}else{
bookMark.insertTextAtBookMark(content.get(bookMarkName), BookMark.REPLACE,"仿宋_GB2312");
}
}
}
// 保存
File newFile = new File(targetFile);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(newFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
document.write(fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void nioTransferCopy(String source, String target) throws IOException {
FileChannel in = null;
FileChannel out = null;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(source);
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
in.transferTo(0, in.size(), out);
} finally {
try {
if (inStream != null)
inStream.close();
if (in != null)
in.close();
if (out != null)
out.close();
if (outStream != null)
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 生成CSV文件
* @param objList 输出队列
* @param fields 字段排序数组
* @param outputFilePathAndName 输出文件路径和名字
* @param charset 编码(为空时默认UTF-8)
* @param lineSeparator(为空时默认\r\n)
*/
public static void createCSVFile(List<Object> objList, String[] fields,String outputFilePathAndName, String charset, String lineSeparator) throws Exception {
StringBuilder outputContent = new StringBuilder();
for (Object obj : objList) {
Class clazz = obj.getClass();
StringBuilder outputline = new StringBuilder();
for (String field : fields) {
PropertyDescriptor pd = new PropertyDescriptor(field, clazz);
Method getMethod = pd.getReadMethod();// 获得get方法
if (pd != null) {
outputline.append((String) getMethod.invoke(obj)).append(verticalLine);
}
}
if (outputline.length() > 1) {
outputline.deleteCharAt(outputline.length() - 1);
}
outputContent.append(outputline.toString()).append(lineSeparator);
}
if (outputContent.length() > 1) {
outputContent.deleteCharAt(outputContent.length() - 1);
}
if (StringHelper.isNullOrEmpty(charset)) {
charset = UTF8;
}
writeFile(outputFilePathAndName, outputContent.toString(), charset);
}
/**
* 将结果写入到csv文件
* @param filePathAndName 包含路径的文件
* @param fileContent 文件中的内容
* @param charset 字符集
* @throws IOException
*/
public static void writeFile(String filePathAndName, String fileContent, String charset) throws IOException {
BufferedWriter writer = null;
try {
File f = new File(filePathAndName);
File folder = new File(filePathAndName.substring(0,filePathAndName.lastIndexOf("/")));
if (!folder.exists()) {
folder.mkdirs();
}
f.createNewFile();
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), charset));
writer.write(fileContent);
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
md5
package com.jl.syoa.srv.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.SignatureException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
public class MD5Utils {
public static Logger log = Logger.getLogger(MD5Utils.class);
/**
* md5字符串
* @param text 需要md5的字符串
* @param key 密钥
* @param input_charset 编码格式
* @return 签名结果
*/
public static String md5(String text, final String key, final String input_charset) {
text = text + key;
return DigestUtils.md5Hex(getContentBytes(text, input_charset));
}
/**
* @param content
* @param charset
* @return
* @throws SignatureException
* @throws UnsupportedEncodingException
*/
private static byte[] getContentBytes(final String content, final String charset) {
if (charset == null || "".equals(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
} catch (final UnsupportedEncodingException e) {
throw new IllegalArgumentException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
}
}
/**
* 对文件进行MD5加密
* @param inputFile 文件路径
* @return String
* @throws Exception
*/
public static String fileMD5(String inputFile) throws Exception{
int bufferSize = 256 * 1024;
FileInputStream fis = null;
DigestInputStream dis = null;
try {
//拿到一个MD5转换器
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
//使用DigestInputStream
fis = new FileInputStream(inputFile);
dis = new DigestInputStream(fis, messageDigest);
//read的过程中进行MD5处理,直到读完文件
byte[] buffer = new byte[bufferSize];
while(dis.read(buffer) > 0);
//获取最终的MessageDigest
messageDigest = dis.getMessageDigest();
//拿到结果,也是字节数组,包含16个元素
byte[] resultByteArray = messageDigest.digest();
//同样,把字节数组转换成字符串
return byteArrayToHex(resultByteArray);
} catch (Exception e) {
log.error("文件MD5加密异常...", e);
return null;
} finally{
if(fis != null){
fis.close();
}
if(dis != null){
dis.close();
}
}
}
/**
* 将字节数组转换成16进制的字符串
* @param byteArray 字节数组
* @return String
*/
private static String byteArrayToHex(byte[] byteArray) {
String stmp = "";
StringBuffer buffer = new StringBuffer();
for(int n = 0; n < byteArray.length; n++){
stmp = Integer.toHexString(byteArray[n] & 0XFF);
if(stmp.length() == 1){
buffer.append("0").append(stmp);
}else{
buffer.append(stmp);
}
if(n < byteArray.length-1){
buffer.append("");
}
}
return buffer.toString();
}
}
package com.jl.syoa.srv.mail;
import java.io.File;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CommonUtil {
/**
* 判断集合是否有重复元素
* @param list 集合
* @return boolean
*/
public static boolean hasSameElem(List list){
if(list != null && list.size() > 0){
return !(list.size() == new HashSet(list).size());
}else{
return false;
}
}
/**
* 快速去重(去重后元素顺序改变)
* @param originalList
* @return
*/
public static List rmSameElem(List originalList){
if(originalList != null && originalList.size() > 0){
return new ArrayList(new HashSet(originalList));
}
return null;
}
/**
* 去重(不改变元素顺序)
* @param originalList
* @return
*/
public static List rmSameElemWithOrder(List originalList){
if(originalList != null && originalList.size() > 0){
Set set = new HashSet();
List newList = new ArrayList();
for(Object elem : originalList){
if(set.add(elem)){
newList.add(elem);
}
}
return newList;
}
return null;
}
/**
* 获取当前时间字符串
* @return String
*/
public static String getNowDateStr(){
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}
/**
* 获取当前时间字符串
* @return String
*/
public static String getNowDateStr(String pattern){
if(pattern != null && !pattern.equals("")){
return new SimpleDateFormat(pattern).format(new Date());
}else{
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}
}
/**
* 获取昨天时间字符串
* @param pattern 字符串样式
* @return String
*/
public static String getYesterdayStr(String pattern){
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE, -1);
Date thisDate = calendar.getTime();
return new SimpleDateFormat(pattern).format(thisDate);
}
/**
* 将时间转换为字符串
* @param date 时间
* @return String
*/
public static String getDateStr(Date date){
if(date != null){
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
}else{
return "";
}
}
/**
* 将timestamp转换为字符串
* @param timeStamp 时间
* @return String
*/
public static String getDateStr(Timestamp timeStamp){
if(timeStamp != null){
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timeStamp);
}else{
return "";
}
}
/**
* 获取当天X小时之前的时间
* @return
*/
public static String getHoursBefore(int hour){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - hour);
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
}
/**
* 比较两个时间字符串大小
* @param dateStr1 时间字符串1
* @param dateStr2 时间字符串2
* @return 1:时间1>时间2,-1:时间1<时间2,0:两个时间相等
* @throws Exception
*/
public static int compareDateStr(String dateStr1,String dateStr2) throws Exception{
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d1 = formater.parse(dateStr1);
Date d2 = formater.parse(dateStr2);
if(d1.getTime() > d2.getTime()){
return 1;
}else if(d1.getTime() < d2.getTime()){
return -1;
}else{
return 0;
}
}
/**
* 当天的开始时间
* @return long
*/
public static long startOfToday(){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime().getTime();
}
/**
* 获取当天开始时间
* @return String
*/
public static String getStartTime(){
return getDateStr(new Date(startOfToday()));
}
/**
* 当天的结束时间
* @return long
*/
public static long endOfToday(){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTime().getTime();
}
/**
* 获取当天结束时间
* @return String
*/
public static String getEndTime(){
return getDateStr(new Date(endOfToday()));
}
/**
* 获取当前时间
* @return Timestamp
*/
public static Timestamp getNowTimestamp(){
return new Timestamp(new Date().getTime());
}
/**
* 获取前一天开始时间(long)
* @return long
*/
public static long startOfYesterday(String dateStr) throws Exception{
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime().getTime();
}
/**
* 获取前一天开始时间
* @return String
*/
public static String yesterdatStart(String dateStr) throws Exception{
return getDateStr(new Date(startOfYesterday(dateStr)));
}
/**
* 获取前一天结束时间(long)
* @return long
*/
public static long endOfYesterday(String dateStr) throws Exception{
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -1);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTime().getTime();
}
/**
* 获取前一天结束时间
* @return String
*/
public static String yesterdayEnd(String dateStr) throws Exception{
return getDateStr(new Date(endOfYesterday(dateStr)));
}
/**
* 获取上周一开始时间(long)
* @param dateStr 时间点
* @return long
* @throws Exception
*/
public static long getPreMondayStart(String dateStr) throws Exception{
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_WEEK, 1);//本周第一天(周日)
calendar.add(Calendar.DATE, -6);//上周一
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime().getTime();
}
/**
* 获取上周一开始时间
* @param dateStr 时间点
* @return String
* @throws Exception
*/
public static String preMondayStart(String dateStr) throws Exception{
return getDateStr(new Date(getPreMondayStart(dateStr)));
}
/**
* 获取本周日结束时间(long)
* @param dateStr 时间点
* @return long
*/
public static long getThisSundayEnd(String dateStr) throws Exception{
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_WEEK, 1);//本周第一天(周日)
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTime().getTime();
}
/**
* 获取本周日结束时间
* @param dateStr 时间点
* @return String
* @throws Exception
*/
public static String thisSundayEnd(String dateStr) throws Exception{
return getDateStr(new Date(getThisSundayEnd(dateStr)));
}
/**
* 上周六开始时间
* @param dateStr 时间点
* @return String
*/
public static String preSaturdayStart(String dateStr) throws Exception{
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_WEEK, 7);//本周第7天(周六)
calendar.add(Calendar.DATE, -7);//上周六
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date thisDate = calendar.getTime();
return getDateStr(thisDate);
}
/**
* 本周五结束时间
* @param dateStr 时间点
* @return String
* @throws Exception
*/
public static String thisFridayEnd(String dateStr) throws Exception{
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_WEEK, 6);//本周第6天(周五)
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
Date thisDate = calendar.getTime();
return getDateStr(thisDate);
}
/**
* 当一个集合size大于一个数时,分成多个集合
* @param list 该集合
* @param size 集合大小
* @return 多个集合
*/
public static List<List<Object>> getMuchLists(List<Object> list, Integer size){
if(list != null && list.size() > 0 && size != null && size != 0){
List<List<Object>> lists = new ArrayList<List<Object>>();//返回集合
if(list.size() > size){
//集合大小大于参数大小
Integer num = ((list.size()/size == 0)?(list.size()/size):(list.size()/size + 1));//总共分成多少个集合
Integer lastIndex = 0;
for(int i = 0; i < num; i++){
List<Object> newList = new ArrayList<Object>();
lastIndex = (((i+1)==num)?(list.size()):((i+1)*size));
for(int j = i * size; j < lastIndex; j++){
newList.add(list.get(j));
}
lists.add(newList);
}
}else{
//集合大小小于或等于参数大小
lists.add(list);
}
return lists;
}
return null;
}
/**
* 获取文件最后修改时间
* @param file 文件
* @return String
*/
public static String fileLastModifyTime(File file, String formater) throws Exception{
Date date = new Date(file.lastModified());
return new SimpleDateFormat(formater).format(date);
}
/**
* 获取N个月之前月的时间(开始时间,结束时间,月份汉字)
* @param preNum 之前n个月
* @return Map
*/
public static Map<String, String> getMonDate(int preNum){
Map<String, String> moMap = new HashMap<String, String>();
SimpleDateFormat fromater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
if(preNum < 0){
calendar.add(Calendar.MONTH, preNum);
}
calendar.set(Calendar.DAY_OF_MONTH, 1);//一个月第一天
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
String dayFirst = fromater.format(calendar.getTime());
moMap.put("dayFirst", dayFirst);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));//一个月最后一天
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
String dayLast = fromater.format(calendar.getTime());
moMap.put("dayLast", dayLast);//一个月最后一天
int moNum = calendar.get(Calendar.MONTH) + 1;
moMap.put("moCharacter", getMoCharacter(moNum));
return moMap;
}
/**
* 获取月份汉字
* @param moNum
* @return
*/
public static String getMoCharacter(int moNum) {
String rtnStr = "";
if(moNum == 1){
rtnStr = "一月";
}else if(moNum == 2){
rtnStr = "二月";
}else if(moNum == 3){
rtnStr = "三月";
}else if(moNum == 4){
rtnStr = "四月";
}else if(moNum == 5){
rtnStr = "五月";
}else if(moNum == 6){
rtnStr = "六月";
}else if(moNum == 7){
rtnStr = "七月";
}else if(moNum == 8){
rtnStr = "八月";
}else if(moNum == 9){
rtnStr = "九月";
}else if(moNum == 10){
rtnStr = "十月";
}else if(moNum == 11){
rtnStr = "十一月";
}else if(moNum == 12){
rtnStr = "十二月";
}
return rtnStr;
}
/**
* 获取n天前后的开始时间
* @param dayNum n天
* @return String
*/
public static String dayStartTime(int dayNum){
SimpleDateFormat fromater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
if(dayNum != 0){
calendar.add(Calendar.DATE, dayNum);
}
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
String dayFirst = fromater.format(calendar.getTime());
return dayFirst;
}
/**
* 计算两个时间相差月份
* @param startDate 开始时间
* @param endDate 结束时间
* @return Integer
*/
public static Integer calMon(Date startDate, Date endDate){
if(startDate != null && endDate != null){
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(startDate);
cal2.setTime(endDate);
int month = cal2.get(Calendar.MONTH) - cal1.get(Calendar.MONTH);
int year = cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR);
return Math.abs(year*12+month);
}
return null;
}
/**
* 获取当年的第一天
* @return Date
*/
public static Date getCurrYearFirst(){
Calendar currCal = Calendar.getInstance();
int currentYear = currCal.get(Calendar.YEAR);
return getYearFirst(currentYear);
}
/**
* 获取当年的最后一天
* @return Date
*/
public static Date getCurrYearLast(){
Calendar currCal = Calendar.getInstance();
int currentYear = currCal.get(Calendar.YEAR);
return getYearLast(currentYear);
}
/**
* 获取某年第一天日期
* @param year 年份
* @return Date
*/
public static Date getYearFirst(int year){
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.YEAR, year);
Date currYearFirst = calendar.getTime();
return currYearFirst;
}
/**
* 获取某年最后一天日期
* @param year 年份
* @return Date
*/
public static Date getYearLast(int year){
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.YEAR, year);
calendar.roll(Calendar.DAY_OF_YEAR, -1);
Date currYearLast = calendar.getTime();
return currYearLast;
}
/**
* 保留两位小数(四舍五入)
* @param origNum 原小数
* @return Double
*/
public static Double d2Place(Double origNum){
if(origNum != null){
DecimalFormat formatter = new DecimalFormat("#.00");
String numStr = formatter.format(origNum);
return Double.parseDouble(numStr);
}
return null;
}
/**
* 判断一个字符串是否为自然数
* @param numStr
*/
public static boolean isNatureNum(String numStr){
Pattern pattern = Pattern.compile("[1-9]*0?");
Matcher isPosInt = pattern.matcher(numStr);
if(!isPosInt.matches()){
return false;
}
return true;
}
}