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

emi*_*io5 4 java system

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

FTh*_*son 9

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

请注意,这两个操作都不会以毫秒精度返回正常运行时间.

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您的操作系统语言和设置与建议的 SimpleDateFormat 中的内容相匹配,则否决此答案,因为它仅适用于 Windows。如果在操作系统设置中更改日期格式,则日期/时间模式将不匹配。同样的事情,如果您的操作系统语言不是英语,'Statistics since' 将在 net 命令输出中以操作系统语言打印并且不会匹配。因此,答案可能适用于您的计算机,但不适用于国外的客户端站点。 (2认同)

Ste*_*ich 5

使用适用于 Windows、Linux 和 Mac OS的OSHI 库

new SystemInfo().getOperatingSystem().getSystemUptime()
Run Code Online (Sandbox Code Playgroud)