Java 获取CPU、内存、外网IP等硬件信息
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties; import com.sun.management.OperatingSystemMXBean; public class MachineUtils { /**
* 判断服务是否运行
* @param ProcessName 启动这个服务的进程名 带.exe
* @param ServiceName 服务名
* @return 返回运行状态
*/
public static Boolean GetServiceStatue(String ProcessName,String ServiceName) {
String temp = "";
InputStream inputStream=null;
BufferedReader bufferedReader=null;
try {
Process process = Runtime.getRuntime().exec("tasklist /svc");
inputStream = process.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"GBK"));//注意中文编码问题
while ((temp=bufferedReader.readLine())!=null){
if(temp != null && temp.contains(ServiceName) && temp.contains(ProcessName) ) {
bufferedReader.close();
inputStream.close();
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(bufferedReader!=null) {
bufferedReader.close();
}
if(inputStream!=null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
} /**
* 判断服务是否安装
* @param ServiceName 服务名
* @return
*/
public static Boolean GetServiceInstallStatue(String ServiceName) {
String temp = "";
InputStream inputStream = null;
BufferedReader bufferedReader=null;
try {
Process process = Runtime.getRuntime().exec("sc query "+ServiceName);//查询服务是否安装
inputStream = process.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"GBK"));//注意中文编码问题
while ((temp=bufferedReader.readLine())!=null){
if(temp !=null && temp.contains(ServiceName)) {
bufferedReader.close();
inputStream.close();
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(bufferedReader!=null) {
bufferedReader.close();
}
if(inputStream!=null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
} /**
* @param cmd cmd命令或者bat文件,bat文件获取系统权限时会有闪屏
* 获取系统权限的方法
* @echo off
%1 mshta vbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c %~s0 ::","","runas",1)(window.close)
cd /d "%~dp0"
ipconfig
* @return 命令输出内容
*
*/
public static String executeCmd(String cmd) {
String line = null;
BufferedReader br=null;
InputStream inputStream=null;
StringBuffer buffer=new StringBuffer();
try {
Process proc = Runtime.getRuntime().exec(cmd);// 执行命令
inputStream = proc.getInputStream();//执行结果 得到进程的标准输出信息流
br = new BufferedReader(new InputStreamReader(inputStream,"GBK"));
while ((line = br.readLine()) != null) {
buffer.append(line+"\n");
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(br!=null) {
br.close();
}
if(inputStream!=null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return buffer.toString();
} /**
* 获取mac地址
* @return
*/
public static String getLocalMac() {
StringBuffer sb = new StringBuffer();
try {
InetAddress ia = InetAddress.getLocalHost();
byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
for(int i=0; i<mac.length; i++) {
if(i!=0) {
sb.append("-");
}
int temp = mac[i]&0xff;//字节转换为整数
String str = Integer.toHexString(temp);
if(str.length()==1) {
sb.append("0"+str);
}else {
sb.append(str);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString().toUpperCase();
} /**
* 获取操作系统类型
* @return
*/
public static String getOsType() {
Properties props=System.getProperties(); //获得系统属性集
String osName = props.getProperty("os.name"); //操作系统名称
//String osArch = props.getProperty("os.arch"); //操作系统构架
//String osVersion = props.getProperty("os.version"); //操作系统版本
return osName;
} /**
* 获取本地IP
* @return
*/
public static String getLocalIP(){
StringBuilder sb = new StringBuilder();
try {
Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface intf = (NetworkInterface) en.nextElement();
Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
while (enumIpAddr.hasMoreElements()) {
InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
sb.append(inetAddress.getHostAddress().toString()+"\n");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
} /**
* 获取外网ip和所在地
* @return
*/
public static String getRemoteIp() {
InputStream in = null;
StringBuffer buffer = new StringBuffer();
try {
// URL url = new URL("http://www.ip138.com/ip2city.asp"); //创建 URL
URL url = new URL("http://ip.chinaz.com/getip.aspx"); //创建 URL
in = url.openStream(); // 打开到这个URL的流
BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
String inputLine = "";
while ((inputLine = reader.readLine()) != null)
{
buffer.append(inputLine);
}
}catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return buffer.toString();
} /**
* 获取最大可用磁盘
* @return 返回 C D E F....
*/
public static String getMaxDisk() {
long size=0;
String max="";
File[] roots = File.listRoots();
for (File file : roots) {
if( file.getFreeSpace()>size) {
size=file.getFreeSpace();
max=file.getPath().substring(0, 1);
}
// System.out.println("Free space = " + (file.getFreeSpace()/(1024*1024))/1024); //显示GB大小
// System.out.println("Usable space = " + _file.getUsableSpace());
// System.out.println("Total space = " + _file.getTotalSpace());
// System.out.println("used space = " + (_file.getTotalSpace()-_file.getFreeSpace()));
// System.out.println();
}
System.out.println(max);
return max;
} /**
* 获取当前运行路径
* @return
*/
public static String getPath() {
File directory = new File("");//设定为当前文件夹File directory = new File("..")
String path="";
try{
path=directory.getCanonicalPath();//获取标准的路径
//path=directory.getAbsolutePath();//获取绝对路径
}catch(Exception e){ }
return path;
} /**
* 获取内存使用率
* @return
*/
public static String getMemery() {
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
long totalvirtualMemory = osmxb.getTotalSwapSpaceSize();// 总的物理内存+虚拟内存
long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize(); // 剩余的物理内存
Double compare = (Double) (1 - freePhysicalMemorySize * 1.0 / totalvirtualMemory) * 100;
String str = "内存使用率:" + compare.intValue() + "%";
return str;
} /**
* 获取CPU使用率
* @return
*/
public static String getCpuRatio() {
try {
String procCmd = System.getenv("windir") + "//system32//wbem//wmic.exe process get Caption,CommandLine,KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd)); // 取进程信息
Thread.sleep(200);
long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
if (c0 != null && c1 != null) {
long idletime = c1[0] - c0[0];
long busytime = c1[1] - c0[1];
return "CPU使用率:"+ Double.valueOf(100 * (busytime) * 1.0 / (busytime + idletime)).intValue() + "%";
} else {
return "CPU使用率:" + 0 + "%";
}
} catch (Exception ex) {
ex.printStackTrace();
return "CPU使用率:" + 0 + "%";
}
}
private static long[] readCpu(final Process proc) {
long[] retn = new long[2];
try {
proc.getOutputStream().close();
InputStreamReader ir = new InputStreamReader(proc.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line = input.readLine();
if (line == null || line.length() < 10) {
return null;
}
int capidx = line.indexOf("Caption");
int cmdidx = line.indexOf("CommandLine");
int rocidx = line.indexOf("ReadOperationCount");
int umtidx = line.indexOf("UserModeTime");
int kmtidx = line.indexOf("KernelModeTime");
int wocidx = line.indexOf("WriteOperationCount");
long idletime = 0;
long kneltime = 0;
long usertime = 0;
while ((line = input.readLine()) != null) {
if (line.length() < wocidx) {
continue;
}
String caption = substring(line, capidx, cmdidx - 1).trim();
String cmd = substring(line, cmdidx, kmtidx - 1).trim();
if (cmd.indexOf("wmic.exe") >= 0) {
continue;
}
String s1 = substring(line, kmtidx, rocidx - 1).trim();
String s2 = substring(line, umtidx, wocidx - 1).trim();
if (caption.equals("System Idle Process") || caption.equals("System")) {
if (s1.length() > 0)
idletime += Long.valueOf(s1).longValue();
if (s2.length() > 0)
idletime += Long.valueOf(s2).longValue();
continue;
}
if (s1.length() > 0)
kneltime += Long.valueOf(s1).longValue();
if (s2.length() > 0)
usertime += Long.valueOf(s2).longValue();
}
retn[0] = idletime;
retn[1] = kneltime + usertime;
return retn;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
proc.getInputStream().close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
private static String substring(String src, int start_idx, int end_idx) {
byte[] b = src.getBytes();
String tgt = "";
for (int i = start_idx; i <= end_idx; i++) {
tgt += (char) b[i];
}
return tgt;
} }
Java 获取CPU、内存、外网IP等硬件信息的更多相关文章
- Java获得系统的外网IP
关于如何获得系统外网IP?在网上找了好久,大多数解决方案都没法直接用,所以今天和大家分享一段获得外网IP的代码! import java.net.Inet4Address; import java.n ...
- JAVA获取访问者的内网IP地址
/** * 获取访问者内网IP * @return the server ip */ public static String getIntranetIp() { // 本地IP,如果没有配置外网IP ...
- C#获取路由器外网IP,MAC地址
C#实现的获取路由器MAC地址,路由器外网地址.对于要获取路由器MAC地址,一定需要知道路由器web管理系统的用户名和密码.至于获取路由器的外网IP地址,可以不需要知道路由器web管理系统的用户名和密 ...
- C#获取本机的外网IP
/// <summary> /// 功能:获取本地的外网IP地址 /// 作者:黄海 /// 时间:2016-07-22 /// </summary> /// <retu ...
- C#获取本机内网外网IP
using System.Net; # region 获取内.外网Ip /// <summary> /// 获取本地ip地址,优先取内网ip /// </summary> pu ...
- java web获取客户端外网ip和所在区域
@参考文章1.@参考文章2.@参考文章3.@参考文章4,@之前同事的项目 controller @Controller @RequestMapping("/home") publi ...
- JAVA 优先获取外网Ip,再获取内网Ip
1.获取内网Ip private String getLocalhostIp(){ String hostAddress = ""; try { InetAddress addre ...
- java获取外网ip地址
转自:http://blog.163.com/houjunchang_daxue/blog/static/13037938320134543310451/ /** * 获取外网IP.归属地.操作系统 ...
- 根据Request获取客户端IP 内网IP及外网IP
在JSP里,获取客户端的IP地址的方法是:request.getRemoteAddr() ,这种方法在大部分情况下都是有效的.但是在通过了Apache,Squid等反向代理软件就不能获取到客户端的真实 ...
随机推荐
- 腾讯助理PHP开发工程师外包岗面经
校招错过腾讯了,在社招上看到腾讯有招外包岗,要求比正式岗低,于是抱着试一试的心态投了简历,没一会就收到了笔试题,还算简单. 第二天收到面试官的面试邀请,然后去面试了…… 腾讯里面真是漂亮,光是看装潢就 ...
- java由字符型强制转化为整型例题
此Java程序依次输出参数,参数类型为字符型,要求更改程序,使得字符型强制转化为整形,并将这些整数相加,最后输出总和. 原程序: package demo; public class CommandP ...
- 2008-03-18 22:58 oracle基础知识小结
oracle 数据类型: 字段类型 中文说明 限制条件 ...
- 22.struts2-拦截器.md
目录 1.执行的流程时序图 1.执行的流程时序图 回顾: Struts配置: * 通配符.动态方法调用 * 全局跳转配置.配置的默认值.常量配置 * Struts核心业务 * 请求数据的自动封装 (p ...
- Python类的进阶.md
属性绑定 在python中可以给类对象动态的绑定属性 但是由于这种特性,随意动态绑定也会带来麻烦,因此可用__slots__来限制可绑定的属性名称 __slots__的绑定对于子类是不生效的,只对当前 ...
- 推荐一款好用并且免费的markdown软件 Typora
Typora 的linux 安装步骤 sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys BA300B7755AFCFAE su ...
- DAX2012 R3安装
安装程序跟DAX2009大同小异,不过这验证需要的组件也太多了,简直是.NET Framework大阅兵啊,各种版本都需要安装,特别是VC++从2008一直装到2012,有点崩溃... DEMO数据的 ...
- 通过DOS命令批量重命名文件
以下为提供的两种方法:遍历当前目录下的所有文件名以.avi结尾的文件,然后权限规则进行修改(规则含义请自行查找资料).第一种方法有缺陷,更改完所有的文件名后,会多改一次.请斟酌使用.第二种方法解决了第 ...
- BN和滑动平均
BN目的是使得每层训练的输出结果在同一分布下,实验证明不仅可以加速收敛速度,还可以提高准确度 因为如果想要计算所有图像的均值与方差,显然不太现实,所以每次计算每个batch的方差与均值,为了使得每个b ...
- Windows 10 显示中的仅更改文本大小和加粗选项
问题描述: 在Windows 10 1703 之前的版本,在控制面板-显示中,存在如下图中的图形界面设置: 系统升级到Windows 10 1703 或是Windows 10 1709 之后,不再存在 ...