RuntimeUtils
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
public class RunTimeUtils {
private static Runtime runtime = Runtime.getRuntime();
private static Locale defaultLocale = Locale.getDefault();
//中英文标识
private static boolean CNFlag;
static {
CNFlag=defaultLocale.getLanguage().equals("zh")?true:false;
}
/**
* 获得全部内存
* @return
*/
public static String getTotalMemory() {
return CNFlag?"总内存:"+runtime.totalMemory()+" 字节":"totalMemory:"+runtime.totalMemory()+" bytes";
}
/**
* 获得空闲内存
* @return
*/
public static String getFreeMemory() {
return CNFlag?"空闲内存:"+runtime.freeMemory()+" 字节":"Free Memory:"+runtime.freeMemory()+" bytes";
}
/**
* 获得全部处理器
* @return
*/
public static String getTotalCPU() {
return CNFlag?"CPU核数:"+runtime.availableProcessors()+" 核": "CPU Core Nums:"+runtime.availableProcessors()+" C";
}
/**
* 程序结束后执行指定任务,提交实现runnable即可
* @param runnable
*/
public static void addShutDownHook(Runnable runnable) {
Thread thread = new Thread(runnable);
Runtime.getRuntime().addShutdownHook(thread);
}
/**
* 提供命令返回执行的结果
* @param command
* @return
*/
public static List<String> exec(String command){
List<String> result = new LinkedList<String>();
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command);
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
result.add("执行命令行结果:");
while ((line = br.readLine()) != null)
result.add(line);
CNFlag=false? result.add("Process exitValue: " + proc.waitFor()): result.add("执行退出码: " + proc.waitFor());
} catch (Throwable t) {
t.printStackTrace();
}
return result;
}
/**
* 从指定位置文件读取命令
* @param filePath
* @return
*/
public static List<String> execFromFile(String filePath){
List<String> result = new LinkedList<String>();
try
{
//执行命令
Process p = Runtime.getRuntime().exec(filePath);
//取得命令结果的输出流
InputStream fis=p.getInputStream();
//用一个读输出流类去读
InputStreamReader isr=new InputStreamReader(fis);
//用缓冲器读行
BufferedReader br=new BufferedReader(isr);
String line=null;
//直到读完为止
while((line=br.readLine())!=null)
result.add(line);
}
catch (IOException e)
{
e.printStackTrace();
}
return result;
}
public static void main(String[] args) throws Exception {
System.out.println(getTotalMemory());
System.out.println(getFreeMemory());
System.out.println(getTotalCPU());
//猜猜结果是什么
System.out.println("1");
addShutDownHook(new Runnable() {
@Override
public void run() {
System.out.println("2");
}
});
Thread.sleep(1000);
System.out.println("3");
}
}
本文作者:zydjjcpdszylddpll
本文链接:https://www.cnblogs.com/jyfs/p/15682070.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步