java 运行时间,用Java获取系统正常运行时间

How can I determine how long (in milliseconds) a computer has been powered on?

解决方案

In Windows, you can execute the net stats srv command, and in Unix, you can execute the uptime command. Each output must be parsed to acquire the uptime. This method automatically executes the necessary command by detecting the user's operating system.

Note that neither operation returns uptime in millisecond precision.

public static long getSystemUptime() throws Exception {

long uptime = -1;

String os = System.getProperty("os.name").toLowerCase();

if (os.contains("win")) {

Process uptimeProc = Runtime.getRuntime().exec("net stats srv");

BufferedReader in = new BufferedReader(new InputStreamReader(uptimeProc.getInputStream()));

String line;

while ((line = in.readLine()) != null) {

if (line.startsWith("Statistics since")) {

SimpleDateFormat format = new SimpleDateFormat("'Statistics since' MM/dd/yyyy hh:mm:ss a");

Date boottime = format.parse(line);

uptime = System.currentTimeMillis() - boottime.getTime();

break;

}

}

} else if (os.contains("mac") || os.contains("nix") || os.contains("nux") || os.contains("aix")) {

Process uptimeProc = Runtime.getRuntime().exec("uptime");

BufferedReader in = new BufferedReader(new InputStreamReader(uptimeProc.getInputStream()));

String line = in.readLine();

if (line != null) {

Pattern parse = Pattern.compile("((\\d+) days,)? (\\d+):(\\d+)");

Matcher matcher = parse.matcher(line);

if (matcher.find()) {

String _days = matcher.group(2);

String _hours = matcher.group(3);

String _minutes = matcher.group(4);

int days = _days != null ? Integer.parseInt(_days) : 0;

int hours = _hours != null ? Integer.parseInt(_hours) : 0;

int minutes = _minutes != null ? Integer.parseInt(_minutes) : 0;

uptime = (minutes * 60000) + (hours * 60000 * 60) + (days * 6000 * 60 * 24);

}

}

}

return uptime;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值