Get Uptime Operating System Windows, Mac, Linux
This example shows you how you can get the uptime for different operating systems like Windows, Mac or Linux. In windows, you can execute the net stats srv
command. In Unix, you can execute the uptime
command. Both output must be parsed correctly to acquire the uptime.
Note: this is by no means a solution for every environment. There could be subtle differences in a distribution or operating system version. This is rather an example of how you could get the uptime of an operating system.
Get Uptime Operating System
package com.memorynotfound;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GetUpTime {
public static void main(String... args) throws Exception {
long upTime = getSystemUptime();
System.out.println("up time: " + upTime + " ms");
System.out.println("up time: " + TimeUnit.DAYS.convert(upTime, TimeUnit.MILLISECONDS) + " days");
}
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 = TimeUnit.MILLISECONDS.convert(days, TimeUnit.DAYS) +
TimeUnit.MILLISECONDS.convert(hours, TimeUnit.HOURS) +
TimeUnit.MILLISECONDS.convert(minutes, TimeUnit.MINUTES);
}
}
}
return uptime;
}
}
Output Uptime Operating System For Mac os X
up time: 1513380000 ms
up time: 17 days