用Java获取系统正常运行时间 [英] Get system uptime in Java

查看:812
本文介绍了用Java获取系统正常运行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确定计算机已启动多长时间(以毫秒为单位)?

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

推荐答案

在Windows中,您可以执行 net stats srv 命令,在Unix中,您可以执行 uptime 命令。必须解析每个输出以获得正常运行时间。此方法通过检测用户的操作系统自动执行必要的命令。

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;
}

这篇关于用Java获取系统正常运行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆