有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (3) 个答案

  1. # 1 楼答案

    我真的想不出一个不依赖操作系统的方法来做到这一点。 一种选择是使用ManagementFactory.getRuntimeMXBean().getUptime(); 这会返回JVM正常运行时间,所以这并不完全是您想要的,但已经朝着正确的方向迈出了一步

    你到底想用这些数据做什么

  2. # 2 楼答案

    在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;
    }
    
  3. # 3 楼答案

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

    new SystemInfo().getOperatingSystem().getSystemUptime()