Reputation: 974
What is the best way to get the UNIX uptime in Java? Is there a standard Java library/function I could use or should I use Runtime's exec or ProcessBuilder to execute 'uptime'? Thanks
Upvotes: 8
Views: 3927
Reputation: 533920
This is likely to be entirely system dependant but you can use System.nanotime();
System.out.println("/proc/uptime " + new Scanner(new FileInputStream("/proc/uptime")).next());
System.out.println("System.nanoTime " + System.nanoTime() / 1e9);
prints
/proc/uptime 265671.85
System.nanoTime 265671.854834206
Warning: This is unlikely to work on all platforms.
Upvotes: 3
Reputation: 3500
Runtime.getRuntime().exec('uptime');
Did you try this? The only command that does something equivalent to system('uptime');
in java is runTime.exec()
. Thats all I could think of ..
Upvotes: 3
Reputation: 341003
You can read /proc/uptime
:
new Scanner(new FileInputStream("/proc/uptime")).next();
//"1128046.07" on my machine and still counting
From Wikipedia:
Shows how long the system has been on since it was last restarted:
$ cat /proc/uptime
350735.47 234388.90
The first number is the total number of seconds the system has been up. The second number is how much of that time the machine has spent idle, in seconds.
Upvotes: 9