java监控linux服务器CPU,内存等信息

最近公司在做爬虫系统,我接到一个需求是获取服务器CPU,内存等信息。一开始我打算通过linux shell获取然后输出到文件,java读取文件获得。后来回想一切皆文件的linux应该本来就有记录在文件中,经过查找资料,找到了解决方法。
资料参考:http://www.jb51.net/article/75002.htm

* 取得linux系统下的cpu、内存信息  
*  
* */  
public  final  class LinuxSystemTool  
{  
/**  
* get memory by used info  
*  
* @return int[] result  
* result.length==4;int[0]=MemTotal;int[1]=MemFree;int[2]=SwapTotal;int[3]=SwapFree;  
* @throws IOException  
* @throws InterruptedException  
*/ 
public  static  int [] getMemInfo() throws IOException, InterruptedException  
{  
File file = new File( "/proc/meminfo" );  
BufferedReader br = new BufferedReader( new InputStreamReader(  
new FileInputStream(file)));  
int [] result = new  int [ 4 ];  
String str = null ;  
StringTokenizer token = null ;  
while ((str = br.readLine()) != null )  
{  
token = new StringTokenizer(str);  
if (!token.hasMoreTokens())  
continue ;  

str = token.nextToken();  
if (!token.hasMoreTokens())  
continue ;  

if (str.equalsIgnoreCase( "MemTotal:" ))  
result[0 ] = Integer.parseInt(token.nextToken());  
else  if (str.equalsIgnoreCase( "MemFree:" ))  
result[1 ] = Integer.parseInt(token.nextToken());  
else  if (str.equalsIgnoreCase( "SwapTotal:" ))  
result[2 ] = Integer.parseInt(token.nextToken());  
else  if (str.equalsIgnoreCase( "SwapFree:" ))  
result[3 ] = Integer.parseInt(token.nextToken());  
}  

return result;  
}  

/**  
* get memory by used info  
*  
* @return float efficiency  
* @throws IOException  
* @throws InterruptedException  
*/ 
public  static  float getCpuInfo() throws IOException, InterruptedException  
{  
File file = new File( "/proc/stat" );  
BufferedReader br = new BufferedReader( new InputStreamReader(  
new FileInputStream(file)));  
StringTokenizer token = new StringTokenizer(br.readLine());  
token.nextToken();  
int user1 = Integer.parseInt(token.nextToken());  
int nice1 = Integer.parseInt(token.nextToken());  
int sys1 = Integer.parseInt(token.nextToken());  
int idle1 = Integer.parseInt(token.nextToken());  

Thread.sleep(1000 );  

br = new BufferedReader(  
new InputStreamReader( new FileInputStream(file)));  
token = new StringTokenizer(br.readLine());  
token.nextToken();  
int user2 = Integer.parseInt(token.nextToken());  
int nice2 = Integer.parseInt(token.nextToken());  
int sys2 = Integer.parseInt(token.nextToken());  
int idle2 = Integer.parseInt(token.nextToken());  

return ( float )((user2 + sys2 + nice2) - (user1 + sys1 + nice1)) / ( float )((user2 + nice2 + sys2 + idle2) - (user1 + nice1 + sys1 + idle1));  
}  
}  

同理:要获取LINUX的CPU温度(如果文件存在):

InputStreamReader(new FileInputStream(new File("/proc/acpi/thermal_zone/THM/temperature"))

你可能感兴趣的:(java高级编程)