Get Windows PC Uptime using JAVA

programming

This code snippest is about getting the system uptime using JAVA. The way it works is we invoke net stats srv from java using, JAVA Runtime. The command returns the time that the PC has been up for, A sample command in a windows system looks like,

Microsoft Windows [Version 10.0.10240]
(c) 2015 Microsoft Corporation. All rights reserved.

C:\Users\user>net stats srv
Server Statistics for \\DESKTOP-******


Statistics since 3/31/2020 8:49:26 PM


Sessions accepted                  0
Sessions timed-out                 0
Sessions errored-out               0

Kilobytes sent                     60
Kilobytes received                 53

Mean response time (msec)          0

System errors                      0
Permission violations              0
Password violations                0

Files accessed                     88
Communication devices accessed     0
Print jobs spooled                 0

Times buffers exhausted

  Big buffers                      0
  Request buffers                  0

The command completed successfully.


C:\Users\user>

Then the reponse is parsed in while loop and checks for the word Statistics since. Then finding out the uptime is pretty simple, subtract the time from current system time, it will give you the time that your system has been up. The complete code is as follows,

package com.oksbwn.systeminteraction;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
public class OsLoginTime {
    public static long getSystemUptime() throws Exception {
        long uptime = 0000;

        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;
            }
        }
        return uptime / 36000; //in millisecond
    }
}
Bikash Panda
Catch Me On

Related posts