如何使用Java来检测Windows关闭或重启时间?

时间:2016-11-24 10:51:13

标签: java uptime

如何使用java查看windows关机和重启时间可以有人帮忙 我有启动窗口的代码

Process uptimeProc = Runtime.getRuntime().exec("cmd /c systeminfo | find \"System Boot Time:\"");

1 个答案:

答案 0 :(得分:0)

您尝试执行的命令是正确的。

您需要等待或完成该过程并返回输出。在从中获取InputStream之前,请使用waitFor()对象的Process方法。

此示例代码可能会帮助您入门:

    Process uptimeProc = Runtime.getRuntime().exec("cmd /c systeminfo | find \"System Boot Time:\"");
    uptimeProc.waitFor();
    BufferedReader br = new BufferedReader(new InputStreamReader(uptimeProc.getInputStream()));
    String line = null;
    line = br.readLine();
    System.out.println("Boot Time : " + line);
  

<强>更新

尝试使用这两段代码在Windows中查找启动时间和关机时间。这些是根据Windows事件管理器中生成的事件确定的。启动事件ID为6005,关机事件ID为1074。

来源:

https://www.microsoft.com/technet/support/ee/transform.aspx?ProdName=Windows+Operating+System&ProdVer=5.2&EvtID=6005&EvtSrc=EventLog&LCID=1033

https://www.microsoft.com/technet/support/ee/transform.aspx?ProdName=Windows+Operating+System&ProdVer=5.2&EvtID=1074&EvtSrc=User32&LCID=1033

启动时间:

    Process uptimeProc = Runtime.getRuntime().exec("powershell -Command \"get-eventlog System | where-object {$_.EventID -eq '6005'} | sort -desc TimeGenerated\"");
    uptimeProc.waitFor();
    BufferedReader br = new BufferedReader(new InputStreamReader(uptimeProc.getInputStream()));
    String line = null;
    while((line = br.readLine())!=null){
        System.out.println(line);
    }

关机时间:

    Process uptimeProc = Runtime.getRuntime().exec("powershell -Command \"get-eventlog System | where-object {$_.EventID -eq '1074'} | sort -desc TimeGenerated\"");
    uptimeProc.waitFor();
    BufferedReader br = new BufferedReader(new InputStreamReader(uptimeProc.getInputStream()));
    String line = null;
    while((line = br.readLine())!=null){
        System.out.println(line);
    }

您需要执行一些提取。但这应该会让你朝着正确的方向前进。

希望这有帮助!