Search code examples
javauptime

How to dectect windows shutdown or restart time using Java?


how to view windows shutdown and restart time using java can anyone help i have code for startup windows

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

Solution

  • The command that you are trying to execute is correct.

    You will need to wait or the process to complete and return the output. Use the waitFor() method of the Process object before getting the InputStream from it.

    This sample code might get you started:

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

    Update

    Try these two pieces of code for finding the boot time and shutdown time in windows. These are determined based on the events generated in the Windows Event Manager. Boot up event ID is 6005 and that of Shutdown is 1074.

    Sources:

    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

    Boot time:

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

    Shutdown time:

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

    You will need to perform some amount of extraction. But this should hopefully put you in the right direction.

    Hope this helps!