How to get UNIX uptime in Java?

2020-03-01 18:39发布

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

标签: java unix
3条回答
何必那么认真
2楼-- · 2020-03-01 18:47

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.

查看更多
家丑人穷心不美
3楼-- · 2020-03-01 18:54
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 ..

查看更多
叛逆
4楼-- · 2020-03-01 19:02

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.

查看更多
登录 后发表回答