在Java中获得系统正常运行时间

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

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

请注意,这两个操作都不会以毫秒为单位返回正常运行时间

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

对于Windows,您可以通过查询windows WMI来获得uptime以毫秒为单位的准确度

要运行下面的代码,你需要下载Jawin库,并将jawin.dll添加到你的eclipse项目的根目录下

  public static void main(String[] args) throws COMException { String computerName = ""; String userName = ""; String password = ""; String namespace = "root/cimv2"; String queryProcessor = "SELECT * FROM Win32_OperatingSystem"; DispatchPtr dispatcher = null; try { ISWbemLocator locator = new ISWbemLocator( "WbemScripting.SWbemLocator"); ISWbemServices wbemServices = locator.ConnectServer(computerName, namespace, userName, password, "", "", 0, dispatcher); ISWbemObjectSet wbemObjectSet = wbemServices.ExecQuery( queryProcessor, "WQL", 0, null); DispatchPtr[] results = new DispatchPtr[wbemObjectSet.getCount()]; IUnknown unknown = wbemObjectSet.get_NewEnum(); IEnumVariant enumVariant = (IEnumVariant) unknown .queryInterface(IEnumVariant.class); enumVariant.Next(wbemObjectSet.getCount(), results); for (int i = 0; i < results.length; i++) { ISWbemObject wbemObject = (ISWbemObject) results[i] .queryInterface(ISWbemObject.class); System.out.println("Uptime: " + wbemObject.get("LastBootUpTime")); } } catch (COMException e) { e.printStackTrace(); } 

我真的不能想到一个非操作系统依赖的方式来做到这一点。 一个选项是使用ManagementFactory.getRuntimeMXBean().getUptime(); 这将返回您的JVM的正常运行时间,所以不是你正在寻找的东西,但已经迈出了正确的方向。

你究竟想用数据来完成什么?