本文主要是介绍【java工具类】获取服务器ip,时间差,字符串,计算经纬度,MD5加密[加盐与不加盐计算md5]获取临时工作文件夹,获取系统是否是win系列,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
目录
前言
主要封装方法
获取随机字符,自定义长度
md5加密(加盐)
md5加密(不加盐)
过滤掉掉字符串中的空白
获取某个时间间隔以前的时间 时间格式:yyyy-MM-dd HH:mm:ss
获取异常的具体信息
获取ip地址
拷贝属性,为null的不拷贝
判断是否是windows操作系统
替换掉字符串的空格以及空白字符串
获取临时目录
把一个数转化为int ,BigDecimal或者数值对象转化为int
是否为数字,判断对象是否为数字
获取项目路径,一般指的是当前项目的路径
获取文件后缀名 不包含点,文件类型,比如获取图片类型的名称
判断一个对象是否是时间类型
获取当前时间字符串
通过经纬度获取距离(单位:千米)
运行案例
完整的java类代码
前言
应用部署运行之后,需要经常遇到使用同一个功能的工具类,继续获取一些我们需要的参数,,以及参数处理方法,我们经常分别多人开发,后续需要多个人进行统一的合并在一个工具类处理!
主要封装方法
/**
* 默认密码盐长度
*/
public static final int SALT_LENGTH = 6;
获取随机字符,自定义长度
public static String getRandomString(int length) {
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
md5加密(加盐)
public static String md5Hex(String password, String salt) {
return md5Hex(password + salt);
}
md5加密(不加盐)
public static String md5Hex(String str) {
try {
if(StringUtils.isBlank(str)){
return null;
}
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] bs = md5.digest(str.getBytes());
StringBuffer md5StrBuff = new StringBuffer();
for (int i = 0; i < bs.length; i++) {
if (Integer.toHexString(0xFF & bs[i]).length() == 1) {
md5StrBuff.append("0").append(Integer.toHexString(0xFF & bs[i]));
} else {
md5StrBuff.append(Integer.toHexString(0xFF & bs[i]));
}
}
return md5StrBuff.toString();
} catch (Exception e) {
throw new AdminServiceException(BizAdminExceptionEnum.ENCRYPT_ERROR);
}
}
过滤掉掉字符串中的空白
public static String removeWhiteSpace(String value) {
if (isEmpty(value)) {
return "";
} else {
return value.replaceAll("\\s*", "");
}
}
获取某个时间间隔以前的时间 时间格式:yyyy-MM-dd HH:mm:ss
public static String getCreateTimeBefore(int seconds) {
long currentTimeInMillis = Calendar.getInstance().getTimeInMillis();
Date date = new Date(currentTimeInMillis - seconds * 1000);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}
获取异常的具体信息
public static String getExceptionMsg(Throwable e) {
StringWriter sw = new StringWriter();
try {
e.printStackTrace(new PrintWriter(sw));
} finally {
try {
sw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return sw.getBuffer().toString().replaceAll("\\$", "T");
}
获取ip地址
public static String getIp() {
try {
StringBuilder IFCONFIG = new StringBuilder();
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
IFCONFIG.append(inetAddress.getHostAddress().toString() + "\n");
}
}
}
if (isNotEmpty(IFCONFIG.toString())) {
}
return IFCONFIG.toString();
} catch (SocketException ex) {
ex.printStackTrace();
}
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return null;
}
拷贝属性,为null的不拷贝
public static void copyProperties(Object source, Object target) {
BeanUtil.copyProperties(source, target, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
}
判断是否是windows操作系统
public static Boolean isWinOs() {
String os = System.getProperty("os.name");
if (os.toLowerCase().startsWith("win")) {
return true;
} else {
return false;
}
}
替换掉字符串的空格以及空白字符串
public static String replaceBlank(String str) {
String dest = "";
if (str != null) {
Pattern p = compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(str);
dest = m.replaceAll("");
}
return dest;
}
获取临时目录
public static String getTempPath() {
return System.getProperty("java.io.tmpdir");
}
把一个数转化为int ,BigDecimal或者数值对象转化为int
public static Integer toInt(Object val) {
if (val instanceof Double) {
BigDecimal bigDecimal = new BigDecimal((Double) val);
return bigDecimal.intValue();
} else {
return Integer.valueOf(val.toString());
}
}
是否为数字,判断对象是否为数字
public static boolean isNum(Object obj) {
try {
Integer.parseInt(obj.toString());
} catch (Exception e) {
return false;
}
return true;
}
获取项目路径,一般指的是当前项目的路径
public static String getWebRootPath(String filePath) {
try {
String path = ToolUtil.class.getClassLoader().getResource("").toURI().getPath();
path = path.replace("/WEB-INF/classes/", "");
path = path.replace("/target/classes/", "");
path = path.replace("file:/", "");
if (ToolUtil.isEmpty(filePath)) {
return path;
} else {
return path + "/" + filePath;
}
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
获取文件后缀名 不包含点,文件类型,比如获取图片类型的名称
public static String getFileSuffix(String fileWholeName) {
if (ToolUtil.isEmpty(fileWholeName)) {
return "none";
}
int lastIndexOf = fileWholeName.lastIndexOf(".");
return fileWholeName.substring(lastIndexOf + 1);
}
判断一个对象是否是时间类型
public static String dateType(Object o) {
if (o instanceof Date) {
return DateUtil.formatDate((Date) o);
} else {
return o.toString();
}
}
获取当前时间字符串
public static String currentTime() {
return DateUtil.formatDateTime(new Date());
}
通过经纬度获取距离(单位:千米)
public static double getDistance(Double lng1, Double lat1, Double lng2,
Double lat2) {
double radLat1 = rad(lat1);
double radLat2 = rad(lat2);
double a = radLat1 - radLat2;
double b = rad(lng1) - rad(lng2);
double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
+ Math.cos(radLat1) * Math.cos(radLat2)
* Math.pow(Math.sin(b / 2), 2)));
s = s * EARTH_RADIUS;
s = Math.round(s * 10000d) / 10000d;
return s;
}
运行案例
public static void main(String[] args) {
System.out.println("获取一个随机字符串长度[6]:"+getRandomString(SALT_LENGTH));
System.out.println("md5加密【mima123456】之后【添加盐值计算而出】字符串:"+md5Hex("mima123456","women"));
System.out.println("md5加密【mima123456】之后【不添加盐值计算而出】字符串:"+md5Hex("mima123456"));
System.out.println("过滤掉掉字符串[mima 1234 56 ]中的空白字符串:"+removeWhiteSpace("mima 1234 56 "));
System.out.println("获取当前时间:"+currentTime());
System.out.println("获取某个时间间隔以前的时间[60秒之前]:"+getCreateTimeBefore(60));
System.out.println("获取的应用运行在机器的ip:"+getIp());
System.out.println("判断应用运行的服务器是否是win系列系统:"+isWinOs());
System.out.println("南京明孝陵距离中山陵园风景区距离[单位千米]:"+getDistance(118.847373,32.056812,118.861453,32.059739));
System.out.println("获取文件[南京真的是很好的大都市.png]类型:"+getFileSuffix("南京真的是很好的大都市.png"));
System.out.println("获取临时目录:"+getTempPath());
}
结果如下:
获取一个随机字符串长度[6]:zoy1qg
md5加密【mima123456】之后【添加盐值计算而出】字符串:ca0fa80b1b0da8dd859b7c2fdc41429f
md5加密【mima123456】之后【不添加盐值计算而出】字符串:a6d43a253ff8c21267b8200cdb2ae90c
过滤掉掉字符串[mima 1234 56 ]中的空白字符串:mima123456
获取当前时间:2021-02-01 16:47:29
获取某个时间间隔以前的时间[60秒之前]:2021-02-01 16:46:29
获取的应用运行在机器的ip:192.168.184.1
10.26.200.143
192.168.56.1
192.168.137.1
10.105.100.26
判断应用运行的服务器是否是win系列系统:true
南京明孝陵距离中山陵园风景区距离[单位千米]:1.3677
获取文件[南京真的是很好的大都市.png]类型:png
获取临时目录:C:\Users\12131\AppData\Local\Temp\
完整的java类代码
public class ToolUtil extends ValidateUtil {public static DateTimeFormatter getLocalDateTimeFor() {return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");}/*** 默认密码盐长度*/public static final int SALT_LENGTH = 6;/*** 获取随机字符,自定义长度* @Date 2021/01/31 21:55*/public static String getRandomString(int length) {String base = "abcdefghijklmnopqrstuvwxyz0123456789";Random random = new Random();StringBuffer sb = new StringBuffer();for (int i = 0; i < length; i++) {int number = random.nextInt(base.length());sb.append(base.charAt(number));}return sb.toString();}/*** md5加密(加盐)* @Date 2021/01/31 21:56*/public static String md5Hex(String password, String salt) {return md5Hex(password + salt);}/*** md5加密(不加盐)* @Date 2021/01/31 21:56*/public static String md5Hex(String str) {try {if(StringUtils.isBlank(str)){return null;}MessageDigest md5 = MessageDigest.getInstance("MD5");byte[] bs = md5.digest(str.getBytes());StringBuffer md5StrBuff = new StringBuffer();for (int i = 0; i < bs.length; i++) {if (Integer.toHexString(0xFF & bs[i]).length() == 1) {md5StrBuff.append("0").append(Integer.toHexString(0xFF & bs[i]));} else {md5StrBuff.append(Integer.toHexString(0xFF & bs[i]));}}return md5StrBuff.toString();} catch (Exception e) {throw new AdminServiceException(BizAdminExceptionEnum.ENCRYPT_ERROR);}}/*** 过滤掉掉字符串中的空白* @Date 2021/01/31 21:56*/public static String removeWhiteSpace(String value) {if (isEmpty(value)) {return "";} else {return value.replaceAll("\\s*", "");}}/*** 获取某个时间间隔以前的时间 时间格式:yyyy-MM-dd HH:mm:ss* @Date 2021/01/31 21:56*/public static String getCreateTimeBefore(int seconds) {long currentTimeInMillis = Calendar.getInstance().getTimeInMillis();Date date = new Date(currentTimeInMillis - seconds * 1000);SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");return sdf.format(date);}/*** 获取异常的具体信息* @Date 2021/01/31 21:56* @version 2.0*/public static String getExceptionMsg(Throwable e) {StringWriter sw = new StringWriter();try {e.printStackTrace(new PrintWriter(sw));} finally {try {sw.close();} catch (IOException e1) {e1.printStackTrace();}}return sw.getBuffer().toString().replaceAll("\\$", "T");}/*** 获取ip地址** * @Date 2021/01/31 21:56*/public static String getIp() {try {StringBuilder IFCONFIG = new StringBuilder();for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {NetworkInterface intf = en.nextElement();for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {InetAddress inetAddress = enumIpAddr.nextElement();if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {IFCONFIG.append(inetAddress.getHostAddress().toString() + "\n");}}}if (isNotEmpty(IFCONFIG.toString())) {}return IFCONFIG.toString();} catch (SocketException ex) {ex.printStackTrace();}try {return InetAddress.getLocalHost().getHostAddress();} catch (UnknownHostException e) {e.printStackTrace();}return null;}/*** 拷贝属性,为null的不拷贝* @Date 2021/01/31 21:56*/public static void copyProperties(Object source, Object target) {BeanUtil.copyProperties(source, target, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));}/*** 判断是否是windows操作系统* @Date 2021/01/31 21:56*/public static Boolean isWinOs() {String os = System.getProperty("os.name");if (os.toLowerCase().startsWith("win")) {return true;} else {return false;}}/**** 替换掉字符串的空格以及空白字符串* @param str* @return*/public static String replaceBlank(String str) {String dest = "";if (str != null) {Pattern p = compile("\\s*|\t|\r|\n");Matcher m = p.matcher(str);dest = m.replaceAll("");}return dest;}/*** 获取临时目录* @Date 2021/01/31 21:56*/public static String getTempPath() {return System.getProperty("java.io.tmpdir");}/*** 把一个数转化为int ,BigDecimal或者数值对象转化为int* @Date 2021/01/31 21:56*/public static Integer toInt(Object val) {if (val instanceof Double) {BigDecimal bigDecimal = new BigDecimal((Double) val);return bigDecimal.intValue();} else {return Integer.valueOf(val.toString());}}/*** 是否为数字,判断对象是否为数字* @Date 2021/01/31 21:56*/public static boolean isNum(Object obj) {try {Integer.parseInt(obj.toString());} catch (Exception e) {return false;}return true;}/*** 获取项目路径,一般指的是当前项目的路径* @Date 2021/01/31 21:56*/public static String getWebRootPath(String filePath) {try {String path = ToolUtil.class.getClassLoader().getResource("").toURI().getPath();path = path.replace("/WEB-INF/classes/", "");path = path.replace("/target/classes/", "");path = path.replace("file:/", "");if (ToolUtil.isEmpty(filePath)) {return path;} else {return path + "/" + filePath;}} catch (URISyntaxException e) {throw new RuntimeException(e);}}/*** 获取文件后缀名 不包含点,文件类型,比如获取图片类型的名称* @Date 2021/01/31 21:56*/public static String getFileSuffix(String fileWholeName) {if (ToolUtil.isEmpty(fileWholeName)) {return "none";}int lastIndexOf = fileWholeName.lastIndexOf(".");return fileWholeName.substring(lastIndexOf + 1);}/*** 判断一个对象是否是时间类型* @Date 2021/01/31 21:56*/public static String dateType(Object o) {if (o instanceof Date) {return DateUtil.formatDate((Date) o);} else {return o.toString();}}/*** 当前时间** @author stylefeng* @Date 2017/5/7 21:56*/public static String currentTime() {return DateUtil.formatDateTime(new Date());}/*** 渲染树形结构** @param xmSelectTrees* @return java.util.List<com.zeus.pojo.node.XmSelectTree>* @methodName createTreeNode* * @date 2020/6/19*/public static List<XmSelectTree> createTreeNode(List<XmSelectTree> xmSelectTrees) {List<XmSelectTree> xmSelectTreeList = new ArrayList<>();XmSelectTree top = XmSelectTree.builder().id("0").parentId("-1").name("顶级").build();xmSelectTreeList.add(top);if (ToolUtil.isNotEmpty(xmSelectTrees)) {Map<String, List<XmSelectTree>> collect = xmSelectTrees.stream().collect(Collectors.groupingBy(XmSelectTree::getParentId));toChild(collect, top);}return xmSelectTreeList;}private static void toChild(Map<String, List<XmSelectTree>> collect, XmSelectTree parentNode) {List<XmSelectTree> treeMenuNodes = collect.get(parentNode.getId());if (ToolUtil.isNotEmpty(treeMenuNodes)) {//排序treeMenuNodes.stream().sorted(Comparator.comparing(XmSelectTree::getSort)).collect(Collectors.toList());parentNode.setChildren(treeMenuNodes);parentNode.getChildren().forEach(t -> {toChild(collect, t);});}}/*** 获取ip的地址** @return*/public static JSONObject getIpAddresses() {return getAddresses(getIp());}/*** 获取ip的省市* @param ip* @return*/public static JSONObject getAddresses(String ip) {//调用淘宝APIString urlStr = "http://ip.taobao.com/service/getIpInfo.php";String result = HttpUtil.get(urlStr + "?ip=" + ip);JSONObject jsonObject = JSON.parseObject(result);if (jsonObject.containsKey("code") && "0".equals(jsonObject.getString("code"))) {return jsonObject.getJSONObject("data");}return null;}private static double EARTH_RADIUS = 6378.137;private static double rad(double d) {return d * Math.PI / 180.0;}/*** 通过经纬度获取距离(单位:千米)* @param lng1 经度1* @param lat1 纬度1* @param lng2 经度2* @param lat2 纬度2* @return*/public static double getDistance(Double lng1, Double lat1, Double lng2,Double lat2) {double radLat1 = rad(lat1);double radLat2 = rad(lat2);double a = radLat1 - radLat2;double b = rad(lng1) - rad(lng2);double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)+ Math.cos(radLat1) * Math.cos(radLat2)* Math.pow(Math.sin(b / 2), 2)));s = s * EARTH_RADIUS;s = Math.round(s * 10000d) / 10000d;return s;}public static void main(String[] args) {System.out.println("获取一个随机字符串长度[6]:"+getRandomString(SALT_LENGTH));System.out.println("md5加密【mima123456】之后【添加盐值计算而出】字符串:"+md5Hex("mima123456","women"));System.out.println("md5加密【mima123456】之后【不添加盐值计算而出】字符串:"+md5Hex("mima123456"));System.out.println("过滤掉掉字符串[mima 1234 56 ]中的空白字符串:"+removeWhiteSpace("mima 1234 56 "));System.out.println("获取当前时间:"+currentTime());System.out.println("获取某个时间间隔以前的时间[60秒之前]:"+getCreateTimeBefore(60));System.out.println("获取的应用运行在机器的ip:"+getIp());System.out.println("判断应用运行的服务器是否是win系列系统:"+isWinOs());System.out.println("南京明孝陵距离中山陵园风景区距离[单位千米]:"+getDistance(118.847373,32.056812,118.861453,32.059739));System.out.println("获取文件[南京真的是很好的大都市.png]类型:"+getFileSuffix("南京真的是很好的大都市.png"));System.out.println("获取临时目录:"+getTempPath());}
}
这篇关于【java工具类】获取服务器ip,时间差,字符串,计算经纬度,MD5加密[加盐与不加盐计算md5]获取临时工作文件夹,获取系统是否是win系列的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!