1.优化代码

2.fileutil优化
This commit is contained in:
maxf 2018-11-26 18:13:05 +08:00
parent 616eefc067
commit c85efeb4a6
13 changed files with 343 additions and 70 deletions

View File

@ -2,12 +2,12 @@ package com.yexuejc.base.encrypt;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
@ -18,7 +18,6 @@ import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
//import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
/**
* RSA加解密 配置模式
@ -117,7 +116,7 @@ public class RSA {
publicKeyStr = Base64.encodeBase64String(publicKey.getEncoded());
privateKeyStr = Base64.encodeBase64String(privateKey.getEncoded());
}
Map<String, String> keyPairMap = new HashMap<String, String>();
Map<String, String> keyPairMap = new HashMap<String, String>(2);
keyPairMap.put("publicKey", publicKeyStr);
keyPairMap.put("privateKey", privateKeyStr);
@ -302,7 +301,10 @@ public class RSA {
throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
}
byte[] resultDatas = out.toByteArray();
IOUtils.closeQuietly(out);
try {
out.close();
} catch (IOException e) {
}
return resultDatas;
}

View File

@ -16,6 +16,7 @@ import java.security.interfaces.RSAPublicKey;
/**
* RSA加解密 证书模式
* 依赖 {@link RSA}
*
* @ClassName: RSA2
* @Description:
* @author: maxf
@ -55,7 +56,15 @@ public class RSA2 {
*/
public static RSAPrivateKey getPrivateKey(String filepath, String alias, String password) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(filepath), password.toCharArray());
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(filepath);
ks.load(fileInputStream, password.toCharArray());
} finally {
if (fileInputStream != null) {
fileInputStream.close();
}
}
return (RSAPrivateKey) ks.getKey(alias, password.toCharArray());
}

View File

@ -2,8 +2,12 @@ package com.yexuejc.base.encrypt;
/**
* 签名算法类型
* 参考Hutool
* see: https://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Signature
*
* @author maxf
* @ClassName SignAlgorithm
* @Description 签名算法类型 参考Hutool https://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Signature
* @date 2018/11/26 10:25
* @see 1.0
*/
public enum SignAlgorithm {
// The RSA signature algorithm

View File

@ -77,7 +77,7 @@ public class AlgorithmUtil {
* @throw
*/
public static int x36ConvertTo10(String pStr) {
if (pStr == "") {
if (StrUtil.isEmpty(pStr)) {
return 0;
}
// 目标十进制数初始化为0
@ -117,12 +117,12 @@ public class AlgorithmUtil {
if (hexString == null || hexString.length() % 2 != 0) {
return null;
}
String bString = "", tmp;
StringBuffer buf = new StringBuffer();
for (int i = 0; i < hexString.length(); i++) {
tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));
bString += tmp.substring(tmp.length() - 4);
String tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));
buf.append(tmp.substring(tmp.length() - 4));
}
return bString;
return buf.toString();
}
/**
@ -132,7 +132,7 @@ public class AlgorithmUtil {
* @return
*/
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
if (hexString == null || "".equals(hexString)) {
return null;
}
hexString = hexString.toUpperCase();

View File

@ -109,9 +109,9 @@ public class DateTimeUtil {
* @return
*/
public static LocalDate getWeek4First(LocalDate date) {
TemporalAdjuster FIRST_OF_WEEK =
TemporalAdjusters.ofDateAdjuster(localDate -> localDate.minusDays(localDate.getDayOfWeek().getValue() - DayOfWeek.MONDAY.getValue()));
return date.with(FIRST_OF_WEEK);
TemporalAdjuster firstOfWeek = TemporalAdjusters.ofDateAdjuster(localDate ->
localDate.minusDays(localDate.getDayOfWeek().getValue() - DayOfWeek.MONDAY.getValue()));
return date.with(firstOfWeek);
}
/**
@ -130,9 +130,9 @@ public class DateTimeUtil {
* @return
*/
public static LocalDate getWeek4Last(LocalDate date) {
TemporalAdjuster LAST_OF_WEEK =
TemporalAdjusters.ofDateAdjuster(localDate -> localDate.plusDays(DayOfWeek.SUNDAY.getValue() - localDate.getDayOfWeek().getValue()));
return date.with(LAST_OF_WEEK);
TemporalAdjuster lastOfWeek = TemporalAdjusters.ofDateAdjuster(localDate ->
localDate.plusDays(DayOfWeek.SUNDAY.getValue() - localDate.getDayOfWeek().getValue()));
return date.with(lastOfWeek);
}
/**
@ -273,22 +273,22 @@ public class DateTimeUtil {
return df.format(dateTime);
}
public static void main(String[] args) {
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// System.out.println(df.format(zonedDateTime2Date(ZonedDateTime.now())));
// System.out.println(df2.format(date2ZonedDateTime(new Date())));
/** public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(df.format(zonedDateTime2Date(ZonedDateTime.now())));
System.out.println(df2.format(date2ZonedDateTime(new Date())));
// System.out.println(getWeek4First());
System.out.println(getWeek4First());
System.out.println(format(getWeek4First(LocalDate.parse("2018-02-10")).atTime(LocalTime.MIN)));
System.out.println(format(getWeek4Last(LocalDate.parse("2018-02-10")).atTime(LocalTime.MAX)));
// System.out.println(format(getMonth4First().atTime(LocalTime.MIN)));
// System.out.println(format(getMonth4Last().atTime(LocalTime.MAX)));
System.out.println(format(getMonth4First().atTime(LocalTime.MIN)));
System.out.println(format(getMonth4Last().atTime(LocalTime.MAX)));
// System.out.println(format(getYear4First().atTime(LocalTime.MIN)));
// System.out.println(format(getYear4Last().atTime(LocalTime.MAX)));
System.out.println(format(getYear4First().atTime(LocalTime.MIN)));
System.out.println(format(getYear4Last().atTime(LocalTime.MAX)));
}
}*/
}

View File

@ -41,7 +41,8 @@ public class ExcelImportUtil {
* @return
*/
public static boolean validateExcel(String filePath) {
if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
boolean b = filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath));
if (b) {
return false;
}
return true;

View File

@ -1,9 +1,21 @@
package com.yexuejc.base.util;
import sun.misc.BASE64Encoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.CRC32;
/**
* 文件工具类
*
* @author maxf:yexue
* @className FileUtil
* @description 工具类
@ -16,14 +28,31 @@ public class FileUtil {
private static final String TYPE_TAR_GZ = ".tar.gz";
private static final String TAR_GZ = "tar.gz";
public static String getFileType(String fileName) {
if (fileName.lastIndexOf(TYPE_TAR_GZ) > 0) {
return TAR_GZ;
/**
* 获取文件类型不适合所有
* <p>
* 根据文件名称截取.后的文件格式
* </p>
*
* @param fileName
* @return
*/
public static String getFileType(String fileName) throws FileNotFoundException {
try {
if (fileName.lastIndexOf(TYPE_TAR_GZ) > 0) {
return TAR_GZ;
}
return fileName.substring(fileName.lastIndexOf(".") + 1);
} catch (Exception e) {
throw new FileNotFoundException("文件类型未能解析");
}
return fileName.substring(fileName.lastIndexOf(".") + 1);
}
// 判断文件是否存在
/**
* 判断文件是否存在
*
* @param file
*/
public static void judeFileExists(File file) {
if (file.exists()) {
@ -49,9 +78,10 @@ public class FileUtil {
* 4File类的createTempFile方法创建临时文件可以制定临时文件的文件名前缀后缀及文件所在的目录如果不指定目录则存放在系统的临时文件夹下
* 5除mkdirs方法外以上方法在创建文件和目录时必须保证目标文件不存在而且父目录存在否则会创建失败
* </pre>
*
* @return 创建成功失败
*/
public static void judeDirExists(File file) {
public static boolean judeDirExists(File file) {
if (file.exists()) {
if (file.isDirectory()) {
System.out.println("dir exists");
@ -60,9 +90,223 @@ public class FileUtil {
}
} else {
System.out.println("dir not exists, create it ...");
file.mkdirs();
return file.mkdirs();
}
return false;
}
/**
* 获取文件sha1
*
* @param file
* @return
*/
public static String sha1(File file) {
FileInputStream in = null;
try {
in = new FileInputStream(file);
MessageDigest digest = MessageDigest.getInstance("SHA-1");
byte[] buffer = new byte[1024 * 1024 * 10];
int len = 0;
while ((len = in.read(buffer)) > 0) {
digest.update(buffer, 0, len);
}
String sha1 = new BigInteger(1, digest.digest()).toString(16);
int length = 40 - sha1.length();
if (length > 0) {
for (int i = 0; i < length; i++) {
sha1 = "0" + sha1;
}
}
return sha1;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
}
}
return null;
}
/***
* 计算SHA1码
*
* @return String 适用于上G大的文件
* @throws NoSuchAlgorithmException
* */
public static String sha1ByBigFile(File file) {
MessageDigest messagedigest = null;
try {
messagedigest = MessageDigest.getInstance("SHA-1");
FileInputStream in = new FileInputStream(file);
FileChannel ch = in.getChannel();
MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
messagedigest.update(byteBuffer);
return StrUtil.toHex(messagedigest.digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 文件md5
*
* @param file
* @return
*/
public static String md5(File file) {
FileInputStream in = null;
try {
in = new FileInputStream(file);
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024 * 1024 * 10];
int len = 0;
while ((len = in.read(buffer)) > 0) {
digest.update(buffer, 0, len);
}
String md5 = new BigInteger(1, digest.digest()).toString(16);
int length = 32 - md5.length();
if (length > 0) {
for (int i = 0; i < length; i++) {
md5 = "0" + md5;
}
}
return md5;
} catch (IOException e) {
System.out.println(e);
} catch (NoSuchAlgorithmException e) {
System.out.println(e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
System.out.println(e);
}
}
return null;
}
/**
* 对一个文件获取md5值
*
* @return md5串
* @throws NoSuchAlgorithmException
*/
public static String md5ByBigFile(File file) {
MessageDigest messagedigest = null;
try {
messagedigest = MessageDigest.getInstance("MD5");
FileInputStream in = new FileInputStream(file);
FileChannel ch = in.getChannel();
MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0,
file.length());
messagedigest.update(byteBuffer);
return StrUtil.toHex(messagedigest.digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取文件CRC32码
*
* @return String
*/
public static String crc32(File file) {
CRC32 crc32 = new CRC32();
// MessageDigest.get
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[8192];
int length;
while ((length = fileInputStream.read(buffer)) != -1) {
crc32.update(buffer, 0, length);
}
return crc32.getValue() + "";
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取文件base64
*
* @param file
* @return
*/
public static String base64(File file) {
FileInputStream fileInputStream = null;
byte[] data = null;
// 读取图片字节数组
try {
fileInputStream = new FileInputStream(file);
data = new byte[fileInputStream.available()];
fileInputStream.read(data);
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
/* public static void main(String[] args) {
String s1 = base64(new File("C:\\Users\\Administrator\\Desktop\\a.html"));
System.out.println(s1);
String s = sha1(new File("C:\\Users\\Administrator\\Desktop\\a.html"));
String s2 = sha1ByBigFile(new File("C:\\Users\\Administrator\\Desktop\\a.html"));
System.out.println(s);
System.out.println(s2);
String md5 = md5(new File("C:\\Users\\Administrator\\Desktop\\a.html"));
String md52 = md5ByBigFile(new File("C:\\Users\\Administrator\\Desktop\\a.html"));
System.out.println(md5);
System.out.println(md52);
String crc32 = crc32(new File("C:\\Users\\Administrator\\Desktop\\a.html"));
System.out.println(crc32);
}*/
}

View File

@ -47,7 +47,7 @@ public class IdcardValidator {
/**
* 每位加权因子
*/
private static int power[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
private static int[] power = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
/**
* 验证所有的身份证的合法性
@ -167,9 +167,9 @@ public class IdcardValidator {
// 获取第18位
String idcard18Code = idcard.substring(17, 18);
char c[] = idcard17.toCharArray();
char[] c = idcard17.toCharArray();
int bit[] = converCharToInt(c);
int[] bit = converCharToInt(c);
int sum17 = 0;
@ -290,11 +290,11 @@ public class IdcardValidator {
String idcard17 = idcard.substring(0, 6) + year + idcard.substring(8);
char c[] = idcard17.toCharArray();
char[] c = idcard17.toCharArray();
String checkCode = "";
// 将字符数组转为整型数组
int bit[] = converCharToInt(c);
int[] bit = converCharToInt(c);
int sum17 = 0;
sum17 = getPowerSum(bit);

View File

@ -310,8 +310,16 @@ public class ImgUtil {
* @throws IOException
*/
public static byte[] byteImage(String imgUrl) throws IOException {
FileInputStream fis = new FileInputStream(imgUrl);
byte[] rs = new byte[fis.available()];
byte[] rs;
FileInputStream fis = null;
try {
fis = new FileInputStream(imgUrl);
rs = new byte[fis.available()];
} finally {
if (fis != null) {
fis.close();
}
}
return rs;
}

View File

@ -3,7 +3,6 @@ package com.yexuejc.base.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* map相关工具
@ -36,10 +35,11 @@ public class MapRemoveNullUtil {
* @return
*/
public static Map removeNullKey(Map map) {
Set set = map.keySet();
for (Iterator iterator = set.iterator(); iterator.hasNext(); ) {
Object obj = (Object) iterator.next();
remove(obj, iterator);
for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry item = (Map.Entry) it.next();
if (StrUtil.isEmpty(item.getKey())) {
it.remove();
}
}
return map;
}
@ -51,11 +51,11 @@ public class MapRemoveNullUtil {
* @return
*/
public static Map removeNullValue(Map map) {
Set set = map.keySet();
for (Iterator iterator = set.iterator(); iterator.hasNext(); ) {
Object obj = (Object) iterator.next();
Object value = (Object) map.get(obj);
remove(value, iterator);
for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry item = (Map.Entry) it.next();
if (StrUtil.isEmpty(item.getValue())) {
it.remove();
}
}
return map;
}

View File

@ -126,7 +126,7 @@ public final class StrUtil {
return null;
}
Map<String, String> map = new HashMap<String, String>();
Map<String, String> map = new HashMap<String, String>(16);
String[] kv = null;
for (String entry : entrys) {
if (isEmpty(entry)) {
@ -151,7 +151,7 @@ public final class StrUtil {
* @param buf 初始字节数组
* @return 转换后字符串
*/
public static String toHex(byte buf[]) {
public static String toHex(byte[] buf) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
@ -181,7 +181,7 @@ public final class StrUtil {
return null;
}
md.update(str.getBytes());
byte tmp[] = md.digest();
byte[] tmp = md.digest();
return toHex(tmp);
}
@ -215,7 +215,7 @@ public final class StrUtil {
return null;
}
messageDigest.update(str.getBytes());
byte tmp[] = messageDigest.digest();
byte[] tmp = messageDigest.digest();
return toHex(tmp);
}
@ -241,8 +241,9 @@ public final class StrUtil {
* @param str
* @return
*/
private static Pattern pattern = Pattern.compile("[0-9]*");
public static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
@ -262,16 +263,17 @@ public final class StrUtil {
}
StringBuilder coded = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 13; i++) {
coded.append(HEX_CHAR[(int) (Math.random() * 15L) + 1]);
coded.append(HEX_CHAR[random.nextInt(16)]);
}
coded.append(id.substring(0, 11));
for (int i = 0; i < 7; i++) {
coded.append(HEX_CHAR[(int) (Math.random() * 15L) + 1]);
coded.append(HEX_CHAR[random.nextInt(16)]);
}
coded.append(id.substring(11));
for (int i = 0; i < 12; i++) {
coded.append(HEX_CHAR[(int) (Math.random() * 15L) + 1]);
coded.append(HEX_CHAR[random.nextInt(16)]);
}
return coded.toString();
@ -338,7 +340,7 @@ public final class StrUtil {
* @return
*/
public static Map<String, Object> mapSort(Map<String, ?> sortedParams) {
Map<String, Object> map = new HashMap<>();
Map<String, Object> map = new HashMap<>(16);
List<String> keys = new ArrayList<>(sortedParams.keySet());
Collections.sort(keys);
int index = 0;

View File

@ -71,9 +71,12 @@ public class SysUtil {
}
/**
* 异步执行代码块
* 异步执行接口
*/
public interface ThreadRun {
/**
* 执行代码块
*/
void execute();
}
}

View File

@ -23,8 +23,8 @@ public class ThreeDES {
private ThreeDES() {
}
private static final String IV = "1234567-";
private final static String encoding = "utf-8";
public static String IV = "1234567-";
public static String ENCODING = "utf-8";
/**
* DESCBC加密
@ -46,7 +46,7 @@ public class ThreeDES {
Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(IV.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte[] encryptData = cipher.doFinal(src.getBytes(encoding));
byte[] encryptData = cipher.doFinal(src.getBytes(ENCODING));
return Base64.encodeBase64URLSafeString(encryptData);
}
@ -72,7 +72,7 @@ public class ThreeDES {
byte[] decryptData = cipher.doFinal(Base64.decodeBase64(src));
return new String(decryptData, encoding);
return new String(decryptData, ENCODING);
}
/**