一、时间工具类:格式化时间、计算时间
(1)DateUtils.java
package com.lhf;
import java.text.SimpleDateFormat;
/**
* 日期格式化
*
* @description
*
* @author lhf
* @createDate 2017年9月4日
*/
public class DateUtils {
public static String getCurrentDate(String aFormat) {
String tDate = new SimpleDateFormat(aFormat).format(new java.util.Date(System.currentTimeMillis()));
return tDate;
}
public static String getCurrentDate() {
return DateUtils.getCurrentDate("yyyyMMdd");
}
public static String getCurrentTime() {
return DateUtils.getCurrentDate("HHmmss");
}
public static String getCurrentDateAndTime() {
return DateUtils.getCurrentDate("yyyyMMddHHmmss");
}
public static String getCurrentDateAndTimeFormat() {
return DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss");
}
public static String getNewRandomCode(int codeLen) {
//首先定义随机数据源
//根据需要得到的数据码的长度返回随机字符串
java.util.Random randomCode = new java.util.Random();
String strCode = "";
while (codeLen > 0) {
int charCode=randomCode.nextInt(9);
strCode += charCode;
codeLen--;
}
return strCode;
}
public static void main(String[] args) {
System.out.println(getNewRandomCode(20));
System.out.println(getCurrentDate());
System.out.println(getCurrentTime());
System.out.println(getCurrentDateAndTime());
System.out.println(getCurrentDateAndTimeFormat());
}
}
(2)DateUtil.java
package com.utils;
import java.security.InvalidParameterException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import com.shove.Convert;
/**
* 时间工具类
*
* @description
*
* @author lhf
* @createDate 2018年6月25日
*/
public class DateUtil {
/** 1秒对应的毫秒数 */
public static final long MILLIS_IN_A_SECOND = 1000;
/** 1分对应的秒数 */
public static final long SECONDS_IN_A_MINUTE = 60;
/** 1小时对应的分钟数 */
public static final long MINUTES_IN_AN_HOUR = 60;
/** 1天对应的小时数 */
public static final long HOURS_IN_A_DAY = 24;
/** 1星期对应的天数 */
public static final int DAYS_IN_A_WEEK = 7;
/** 1年对应的月数 */
public static final int MONTHS_IN_A_YEAR = 12;
/** 1天对应的毫秒数 */
public static final long millSecondsInOneDay = HOURS_IN_A_DAY * MINUTES_IN_AN_HOUR * SECONDS_IN_A_MINUTE * MILLIS_IN_A_SECOND;
/** 1分钟对应的毫秒数 */
public static final long millSecondsInOneMinute = SECONDS_IN_A_MINUTE * MILLIS_IN_A_SECOND;
/** 时间格式化*/
public static final String DATE_FORMAT = "yyyyMMddHHmmssSSS";
/**
* 获取简单的日期
* @return
*/
public static String getSimpleDate() {
SimpleDateFormat time = new SimpleDateFormat(DATE_FORMAT);
String now = time.format(new Date());
return now;
}
/**
* 日期格式化
*
* @param date 日期
* @param formate 格式,以本类定义的格式为准,可自行添加。
* @return
*/
public static String dateToString(Date date, String formate) {
if (date == null) {
return "";
}
return new SimpleDateFormat(formate).format(date);
}
/**
* 字符串转日期
*
* @param dateString
* @param format 日期格式
* @return
*/
public static Date strToDate(String dateString, String format){
if(dateString == null) {
throw new InvalidParameterException("dateString cannot be null!");
}
try {
return new SimpleDateFormat(format).parse(dateString);
} catch (ParseException e) {
throw new RuntimeException("parse error! [dateString:"+ dateString +";format:"+ format +"]");
}
}
/**
* 计算两个日期之间相差的周年数,忽略时间
*
* @param startDate
* @param endDate
* @return
*/
public static int getYearsBetween(Date startDate, Date endDate) {
if (startDate == null || endDate == null) {
throw new InvalidParameterException("startDate and endDate cannot be null!");
}
if (startDate.after(endDate)) {
throw new InvalidParameterException("startDate cannot be after endDate!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
int year1 = calendar.get(Calendar.YEAR);
int month1 = calendar.get(Calendar.MONTH);
int day1 = calendar.get(Calendar.DATE);
calendar.setTime(endDate);
int year2 = calendar.get(Calendar.YEAR);
int month2 = calendar.get(Calendar.MONTH);
int day2 = calendar.get(Calendar.DATE);
int result = year2 - year1;
if (month2 < month1) {
result--;
} else if (month2 == month1 && day2 < day1) {
result--;
}
return result;
}
/**
* 根据生日获取年龄
*
* @param birthday
* @return
* @description
*/
public static int getAge(Date birthday) {
return getYearsBetween(birthday, new Date()) + 1;
}
/**
* 计算两个时间之间相差的天数,满一天算一天
*
* @param startDate
* @param endDate
* @return
* @description
*/
public static int getDaysDiffFloor(Date startDate,Date endDate){
if (startDate == null || endDate == null) {
throw new InvalidParameterException("startDate and endDate cannot be null!");
}
if (startDate.after(endDate)) {
throw new InvalidParameterException("startDate cannot be after endDate!");
}
double days = Math.floor((endDate.getTime() - startDate.getTime()) / (double)millSecondsInOneDay); //满一天算一天
return Convert.strToInt(String.format("%.0f", days), 0);
}
/**
* 计算两个时间之间相差的天数,不满一天按一天算
*
* @param startDate
* @param endDate
* @return
* @description
*/
public static int getDaysDiffCeil(Date startDate,Date endDate){
if (startDate == null || endDate == null) {
throw new InvalidParameterException("startDate and endDate cannot be null!");
}
if (startDate.after(endDate)) {
throw new InvalidParameterException("startDate cannot be after endDate!");
}
double days = Math.ceil((endDate.getTime() - startDate.getTime()) / (double)millSecondsInOneDay); //不满一天按一天算
return Convert.strToInt(String.format("%.0f", days), 0);
}
/**
* 统计两个日期之间包含的天数,忽略时间
*
* @param startDate
* @param endDate
* @return
* @description
*/
public static int getDaysBetween(Date startDate, Date endDate) {
if (startDate == null || endDate == null) {
throw new InvalidParameterException("startDate and endDate cannot be null!");
}
Date _startDate = org.apache.commons.lang.time.DateUtils.truncate(startDate, Calendar.DATE);
Date _endDate = org.apache.commons.lang.time.DateUtils.truncate(endDate,Calendar.DATE);
if (_startDate.after(_endDate)) {
throw new InvalidParameterException("startDate cannot be after endDate!");
}
return (int) ((_endDate.getTime() - _startDate.getTime()) / millSecondsInOneDay);
}
/**
* 计算两个时间之间相差的分钟数,满一分钟算一分钟
*
* @param startDate
* @param endDate
* @return
* @description
*/
public static long getMinutesDiffFloor(Date startDate,Date endDate){
if (startDate == null || endDate == null) {
throw new InvalidParameterException("startDate and endDate cannot be null!");
}
if (startDate.after(endDate)) {
throw new InvalidParameterException("startDate cannot be after endDate!");
}
double days = Math.floor((endDate.getTime() - startDate.getTime()) / (double)millSecondsInOneMinute);
return Convert.strToLong(String.format("%.0f", days), 0);
}
/**
* 日期增加
*
* @param date 日期
* @param calendarType 增加类型,如:Calendar.YEAR,Calendar.DAY_OF_YEAR,Calendar.MONTH
* @param value
* @return
*/
public static Date addDate(Date date,int calendarType,int calendarValue){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(calendarType, calendarValue);
return calendar.getTime();
}
/**
* 日期增加n年
*
* @param date 日期
* @param year 年数
* @return
*/
public static Date addYear(Date date,int year) {
return addDate(date,Calendar.YEAR, year);
}
/**
* 日期增加n月
*
* @param date 日期
* @param month 月数
* @return
*
* @author huangyunsong
* @createDate 2015年12月21日
*/
public static Date addMonth(Date date,int month) {
return addDate(date,Calendar.MONTH, month);
}
/**
* 日期增加n天
*
* @param date 日期
* @param day 天数
* @return
*/
public static Date addDay(Date date,int day) {
return addDate(date,Calendar.DAY_OF_YEAR, day);
}
/**
* 日期减少n年
*
* @param date 日期
* @param year 年数
* @return
*/
public static Date minusYear(Date date,int year) {
return addDate(date,Calendar.YEAR, -year);
}
/**
* 日期减少n月
*
* @param date 日期
* @param month 月数
* @return
*/
public static Date minusMonth(Date date,int month) {
return addDate(date,Calendar.MONTH, -month);
}
/**
* 日期减少n天
*
* @param date 日期
* @param day 天数
* @return
*/
public static Date minusDay(Date date,int day) {
return addDate(date,Calendar.DAY_OF_YEAR, -day);
}
/**
* 获取年
* @param time
* @return
*/
public static int getYear(Date time) {
if (time == null) {
throw new InvalidParameterException("time cannot be null!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
return calendar.get(Calendar.YEAR);
}
/**
* 获取当前时间年
* @return
*/
public static int getCurrentYear() {
return getYear(new Date());
}
/**
* 获取月
* @param time
* @return
*/
public static int getMonth(Date time) {
if (time == null) {
throw new InvalidParameterException("time cannot be null!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
return calendar.get(Calendar.MONTH) + 1;
}
/**
* 获取当前时间月
* @return
*/
public static int getCurrentMonth() {
return getMonth(new Date());
}
/**
* 获取日
* @param time
* @return
*/
public static int getDay(Date time) {
if (time == null) {
throw new InvalidParameterException("time cannot be null!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
return calendar.get(Calendar.DAY_OF_MONTH);
}
/**
* 获取当前时间日
* @return
*/
public static int getCurrentDay() {
return getDay(new Date());
}
/**
* 判断date1是否在date2之后,忽略时间部分
*
* @param date1
* @param date2
* @return
*/
public static boolean isDateAfter(Date date1, Date date2) {
Date theDate1 = org.apache.commons.lang.time.DateUtils.truncate(date1,Calendar.DATE);
Date theDate2 = org.apache.commons.lang.time.DateUtils.truncate(date2,Calendar.DATE);
return theDate1.after(theDate2);
}
/**
* 判断date1是否在date2之前,忽略时间部分
*
* @param date1
* @param date2
* @return
*/
public static boolean isDateBefore(Date date1, Date date2) {
return isDateAfter(date2, date1);
}
/**
* 判断date1是否在date2之后 如:“2015-12-06 12:05:15”.after("2015-12-06 12:17:16") = true
*
* @author liudong
* @createDate 2015年12月24日
* @param val
* @param scale
* @return
*/
public static boolean isDatetimeAfter(Date date1, Date date2) {
return date1.after(date2);
}
/**
* 判断time1是否在time2之后,忽略日期部分
*
* @param time1
* @param time2
* @return
*/
public static boolean isTimeAfter(Date time1, Date time2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
calendar1.set(1900, 1, 1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.set(1900, 1, 1);
return calendar1.after(calendar2);
}
/**
* 判断time1是否在time2之前,忽略日期部分
*
* @param time1
* @param time2
* @return
*/
public static boolean isTimeBefore(Date time1, Date time2) {
return isTimeAfter(time2, time1);
}
/**
* 判断两个日期是否同一天(忽略时间部分)
*
* @param date1
* @param date2
* @return
*/
public static boolean isSameDay(Date date1, Date date2) {
return org.apache.commons.lang.time.DateUtils.isSameDay(date1, date2);
}
/**
* 判断是否过期
*
* @param validTime 生产日期
* @param time 有效期 单位秒
* @return
*/
public static boolean isInValidTime(Date validTime, int time){
long currTime = System.currentTimeMillis();
long valid = validTime.getTime();
return ((currTime - valid) < time*1000);
}
/**
* 获取时间的时间轴表示
* @param date
* @return
*/
public static String getTimeLine(Date date){
long now = new Date().getTime();
long da1 = date.getTime();
String timeline = "";
if(now>da1){//之前
long a = now-da1;
if(a/1000==0){
timeline = "刚刚";
}else {
long a1 = a/1000;
if(a1<60){
timeline = a1+"秒前";
} else{
long b = a1/60;
if(b<60){
if(b>30){
timeline = "半小时前";
}else{
timeline = b+"分钟前";
}
}else{
long c = b/60;
if(c<24){
timeline = c+"小时前";
}else {
long d = c/24;
if(d<30){
if(d>7){
timeline = (d/7)+"周前";
}else{
timeline = d+"天前";
}
} else{
long e = d/30;
if(e<12){
timeline = e+"月前";
} else{
timeline = dateToString(date, "yy/MM/dd");
}
}
}
}
}
}
} else {
long a = da1-now;
if(a/1000==0){
timeline = "刚刚";
}else {
long a1 = a/1000;{
if(a1<60){
timeline = a1+"秒后";
} else{
long b = a1/60;
if(b<60){
if(b==30){
timeline = "半小时后";
}else{
timeline = b+"分钟后";
}
}else{
long c = b/60;
if(c<24){
timeline = c+"小时后";
}else {
long d = c/24;
if(d<30){
if(d%7==0){
timeline = (d/7)+"周后";
}else{
timeline = d+"天后";
}
} else{
long e = d/30;
if(e<12){
timeline = e+"月后";
} else{
timeline = dateToString(date, "yy/MM/dd");
}
}
}
}
}
}
}
}
return timeline;
}
/**
* 获取当前月份的第一天
*
* @author liudong
* @createDate 2015年12月24日
* @param val
* @param scale
* @return
*/
public static String getMonthFirstDay() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
String s = sdf.format(calendar.getTime());
StringBuffer str = new StringBuffer().append(s).append(" 00:00:00");
return str.toString();
}
/**
* 获取当前月份的最后一天
*
* @author liudong
* @createDate 2015年12月24日
* @param val
* @param scale
* @return
*/
public static String getMonthLastDay() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
String s = sdf.format(calendar.getTime());
StringBuffer str = new StringBuffer().append(s).append(" 23:59:59");
return str.toString();
}
/**
* 获取今天次日的时间
* 比如现在时间是:2018-07-03 14:53:35
* 次日是:2018-07-04 00:00:00
* DateUtil.getTodayNextDay(DateUtil.addDay(new Date(), 1))
*
* @return
*
* @author liuhefei
* @createDate 2018年7月3日
*/
public static String getTodayNextDay(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
String s = sdf.format(date);
StringBuffer str = new StringBuffer().append(s).append(" 00:00:00");
return str.toString();
}
/**
* 得到当前时间距2013-11-01 00:00:00的小时数
* @return
*/
public static String getHours(){
SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = simple.parse("2013-11-01 00:00:00");
} catch (ParseException e) {
e.printStackTrace();
}
long millisecond=System.currentTimeMillis()-date.getTime();
long temp = 1000*60*60 ;
long hours = millisecond/temp;
return Long.toString(hours);
}
/**
* 获得当前周- 周一的日期
*
* @return
*/
public static String getCurrentMonday() {
int mondayPlus = getMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(Calendar.DATE, mondayPlus);
Date monday = currentDate.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
String preMonday = sdf.format(monday);
return preMonday;
}
public static int getMondayPlus() {
Calendar cd = Calendar.getInstance();
// 获得今天是一周的第几天,星期日是第一天,星期一是第二天......
int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == 1) {
return -6;
} else {
return 2 - dayOfWeek;
}
}
/**
* 获得当前周- 周日的日期
*
* @return
*/
public static String getPreviousSunday() {
int mondayPlus = getMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(Calendar.DATE, mondayPlus + 6);
Date monday = currentDate.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
String preMonday = sdf.format(monday);
return preMonday;
}
/**
* 返回2个日期相差的天数
* @param fDate
* @param oDate
* @return
*/
public static int getIntervalDays(Date fDate, Date oDate) {
if (null == fDate || null == oDate) {
return -1;
}
long intervalMilli = oDate.getTime() - fDate.getTime();
return (int) (intervalMilli / (24 * 60 * 60 * 1000));
}
/**
* 判断date1是否与date2相等,忽略时间部分
*
* @param date1
* @param date2
* @return
*/
public static boolean isDateEqual(Date date1, Date date2) {
Date theDate1 = org.apache.commons.lang.time.DateUtils.truncate(date1,Calendar.DATE);
Date theDate2 = org.apache.commons.lang.time.DateUtils.truncate(date2,Calendar.DATE);
return theDate1.equals(theDate2);
}
/**
* 日期格式化
*
* @param date
* @param format
*
* @return
*/
public static Date dateToDate(Date date, String format) {
if (date == null) {
throw new InvalidParameterException("date cannot be null!");
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
Date newDate = null;
String dateStr = DateUtil.dateToString(date, format);
try {
newDate = simpleDateFormat.parse(dateStr);
} catch (ParseException e) {
throw new RuntimeException("parse error! [dateString:" + dateStr + ";format:" + format + "]");
}
return newDate;
}
/*
public static void main(String[] args) {
Date date = new Date();
Date date1 = new Date();
Date birthday = strToDate("19940705", "yyyyMMdd");
//获取简单的日期
System.out.println(getSimpleDate() + "\n");
//日期格式化
System.out.println(dateToString(date, "yyyyMMddHH-mmssSSS"));
//字符串转日期
System.out.println(strToDate("20180705", "yyyyMMdd"));
//根据生日获取年龄
System.out.println("你的年龄:"+getAge(birthday));
//计算两个日期质检相差的天数
System.out.println(getDaysDiffFloor(date, date1));
System.out.println("------------------");
//日期增加
System.out.println(addDate(date, Calendar.YEAR, 5)); //当前时间加5年
System.out.println(addDate(date, Calendar.MONTH, 5)); //当前时间加5个月
System.out.println(addDate(date, Calendar.DAY_OF_MONTH, 5)); //当前时间加5年
System.out.println("------------------");
//获取当前时间的年月日
System.out.println(getYear(date) + "-" + getMonth(date) + "-" + getDay(date));
//判断date是否在date1之后,忽略时间部分
System.out.println(isDateAfter(date, date1));
//获取时间的时间轴
System.out.println(getTimeLine(date));
//获取当前月份的第一天
System.out.println("本月的第一天:" + getMonthFirstDay());
System.out.println("本月的最后一天:" + getMonthLastDay());
//获取今天次日的时间
System.out.println("今天次日的时间是:"+getTodayNextDay(date));
//得到当前时间距2013-11-01 00:00:00的小时数
System.out.println(getHours());
//获取本周周一和周日的日期
System.out.println("本周周一的日期:" + getCurrentMonday());
System.out.println("本周周日的日期:" + getPreviousSunday());
//返回两个日期相差的天数
System.out.println(getIntervalDays(date,date1));
//判断两个日期是否相等,忽略时分秒
System.out.println(isDateEqual(date,date1));
//计算两个日期相差的周年数
System.out.println(getYearsBetween(date,addDate(date, Calendar.YEAR, 5)));
}*/
public static void main(String[] args) {
System.out.println(getTodayNextDay(new Date()));
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());
System.out.println(addDay(new Date(), 1));
Date date = addDay(new Date(), 1);
System.out.println(getTodayNextDay(date));
System.out.println("--------------");
System.out.println(getTodayNextDay(addDay(new Date(), 1)));
System.out.println(addMonth(new Date(), 1));
System.out.println(getTodayNextDay(addDay(addMonth(new Date(), 1), 1)));
}
}
二、统计一个项目工程的文件数、代码行数、注释行数、空白行数
CodeCounder.java
package com.lhf;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/**
* 代码行数统计
*
* @description
*
* @author lhf
* @createDate 2018年6月12日
*/
public class CodeCounter {
/**
* 代码行数统计
*/
public static void main(String[] args) {
String file = CodeCounter.class.getResource("/").getFile();
//String path = file.replace("target/test-classes", "src");
//String path = file.replace("/JavaUtil/src/com/lhf/CodeCounter.java", "src");
String path="D:/code/java1/JavaUtil/src";
ArrayList al = getFile(new File(path));
for (File f : al) {
if (f.getName().matches(".*\\.java$")){ // 匹配java格式的文件
count(f);
System.out.println(f);
}
}
System.out.println("统计文件:" + files);
System.out.println("代码行数:" + codeLines);
System.out.println("注释行数:" + commentLines);
System.out.println("空白行数:" + blankLines);
}
static long files = 0;
static long codeLines = 0;
static long commentLines = 0;
static long blankLines = 0;
static ArrayList fileArray = new ArrayList();
/**
* 获得目录下的文件和子目录下的文件
* @param f
* @return
*/
public static ArrayList getFile(File f) {
File[] ff = f.listFiles();
for (File child : ff) {
if (child.isDirectory()) {
getFile(child);
} else
fileArray.add(child);
}
return fileArray;
}
/**
* 统计方法
* @param f
*/
private static void count(File f) {
BufferedReader br = null;
boolean flag = false;
try {
br = new BufferedReader(new FileReader(f));
String line = "";
while ((line = br.readLine()) != null) {
line = line.trim(); // 除去注释前的空格
if (line.matches("^[ ]*$")) { // 匹配空行
blankLines++;
} else if (line.startsWith("//")) {
commentLines++;
} else if (line.startsWith("/*") && !line.endsWith("*/")) {
commentLines++;
flag = true;
} else if (line.startsWith("/*") && line.endsWith("*/")) {
commentLines++;
} else if (flag == true) {
commentLines++;
if (line.endsWith("*/")) {
flag = false;
}
} else {
codeLines++;
}
}
files++;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
br = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
三、获取你电脑的Mac地址
MacUtils.java
package com.lhf;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* MAC地址工具
*
* @description
*
* @author lhf
* @createDate 2017年9月12日
*/
public class MacUtils {
/**
* 获取当前操作系统名称. return 操作系统名称 例如:windows,Linux,Unix等.
*/
public static String getOSName() {
return System.getProperty("os.name").toLowerCase();
}
/**
* 获取Unix网卡的mac地址.
*
* @return mac地址
*/
public static String getUnixMACAddress() {
String mac = null;
BufferedReader bufferedReader = null;
Process process = null;
try {
/**
* Unix下的命令,一般取eth0作为本地主网卡 显示信息中包含有mac地址信息
*/
process = Runtime.getRuntime().exec("ifconfig eth0");
bufferedReader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line = null;
int index = -1;
while ((line = bufferedReader.readLine()) != null) {
/**
* 寻找标示字符串[hwaddr]
*/
index = line.toLowerCase().indexOf("hwaddr");
/**
* 找到了
*/
if (index != -1) {
/**
* 取出mac地址并去除2边空格
*/
mac = line.substring(index + "hwaddr".length() + 1).trim();
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
bufferedReader = null;
process = null;
}
return mac;
}
/**
* 获取Linux网卡的mac地址.
*
* @return mac地址
*/
public static String getLinuxMACAddress() {
String mac = null;
BufferedReader bufferedReader = null;
Process process = null;
try {
/**
* linux下的命令,一般取eth0作为本地主网卡 显示信息中包含有mac地址信息
*/
process = Runtime.getRuntime().exec("ifconfig eth0");
bufferedReader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line = null;
int index = -1;
while ((line = bufferedReader.readLine()) != null) {
index = line.toLowerCase().indexOf("硬件地址");
/**
* 找到了
*/
if (index != -1) {
/**
* 取出mac地址并去除2边空格
*/
mac = line.substring(index + 4).trim();
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
bufferedReader = null;
process = null;
}
// 取不到,试下Unix取发
if (mac == null){
return getUnixMACAddress();
}
return mac;
}
/**
* 获取widnows网卡的mac地址.
*
* @return mac地址
*/
public static String getWindowsMACAddress() {
String mac = null;
BufferedReader bufferedReader = null;
Process process = null;
try {
/**
* windows下的命令,显示信息中包含有mac地址信息
*/
process = Runtime.getRuntime().exec("ipconfig /all");
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
int index = -1;
while ((line = bufferedReader.readLine()) != null) {
/**
* 寻找标示字符串[physical address]
*/
// index = line.toLowerCase().indexOf("physical address");
// if (index != -1) {
if (line.split("-").length == 6){
index = line.indexOf(":");
if (index != -1) {
/**
* 取出mac地址并去除2边空格
*/
mac = line.substring(index + 1).trim();
}
break;
}
index = line.toLowerCase().indexOf("物理地址");
if (index != -1) {
index = line.indexOf(":");
if (index != -1) {
/**
* 取出mac地址并去除2边空格
*/
mac = line.substring(index + 1).trim();
}
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
bufferedReader = null;
process = null;
}
return mac;
}
public static String getMac(){
String os = getOSName();
String mac;
if (os.startsWith("windows")) {
mac = getWindowsMACAddress();
} else if (os.startsWith("linux")) {
mac = getLinuxMACAddress();
} else {
mac = getUnixMACAddress();
}
return mac == null ? "" : mac;
}
/**
* 测试用的main方法.
*
* @param argc 运行参数.
*/
public static void main(String[] argc) {
String os = getOSName();
System.out.println("os: " + os);
if (os.startsWith("windows")) {
String mac = getWindowsMACAddress();
System.out.println("mac: " + mac);
} else if (os.startsWith("linux")) {
String mac = getLinuxMACAddress();
System.out.println("mac: " + mac);
} else {
String mac = getUnixMACAddress();
System.out.println("mac: " + mac);
}
}
}
由于篇幅问题,就分享到这里,后期还会不断更新,请诸君多多支持!如果对你有帮助,就给我点个赞吧!
点击查看更多内容
16人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦