java 篇 之ProcessBulider , Process, RunTime, System

本文介绍了Java中进程管理的相关知识,包括使用Process类创建并获取进程信息的方法,通过Runtime执行命令获取网卡信息的实例,ProcessBuilder类的强大功能及使用方法,以及如何利用System类获取系统信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、Process

process 是 java提供创建一个进程,并获取进程的信息的一个类,主要提供了

getInputStream() //获取输入信息
getErrorStream() //获取错误输出信息
getOutputStream() //获取输出信息
waitFor() // 等待子进程退出,也就是等待cpu的资源

2、RunTime

在jdk 1.0的时候,java 提供了RunTime来创建Process,并提供执行命令

比如,我要获取网卡的信息

public static void main(String[] args) throws IOException, InterruptedException {
    Process process = Runtime.getRuntime().exec("ipconfig");  //穿件进程

    if(process.waitFor()!=0){  //等待进程启动
        try (BufferedInputStream inputStream = new BufferedInputStream(process.getErrorStream())){
            StringBuilder builder = new StringBuilder();
            byte [] bytes = new byte[1024];
            while (inputStream.read(bytes)!=0){
                builder.append(new String(bytes));
            }
            System.out.println("错误信息:"+builder.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    
    //获取进程执行命令ipconfig的信息
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("gbk")))){
        String s = null;
        while ((s=reader.readLine())!=null){
            System.out.println(s);
        }
    }catch (Exception e){

    }
}

该类提供了加载本地库,gc,获取内存信息

3、ProcessBulider

ProcessBulider 是jdk1.5提供的一个线程管理器,他比RunTime的功能更强大,可以获取到操作系统的系统变量,和改变工作目录

ProcessBuilder processBuilder = new ProcessBuilder("ipconfig");
Process process = processBuilder.start(); //用这样的方式创建进程
public Map<String,String> environment() //获取环境变量
public ProcessBuilder directory(File directory) //改变工作目录

4、System

这个类是jdk1.0的类,主要是提供获取系统的信息

这个类也提供了获取环境变量、加载库、gc等功能

但是这个类提供了一些其他我们常用的类,比如

public static String getProperty(String key, String def) //获取属性变量
public static native void arraycopy(Object src,  int  srcPos,
                                    Object dest, int destPos,
                                    int length); //数组copy功能

比如,我们把Properties(本质上是个HashTable)文件的变量放入,要使用的时候在取出

File file = new File("C:\\Users\\ping\\IdeaProjects\\studyJava\\desc");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))){
    String s = null;
    while ((s=reader.readLine())!=null){
        String [] kv = s.split("=");
        System.setProperty(kv[0],kv[1]);
    }
}catch (Exception e){
    e.printStackTrace();
}

String value = System.getProperty("test");
System.out.println(value);

 

 

 

 

 

 

 

 

 

 

 

 

 

转载于:https://my.oschina.net/chenping12/blog/1524303

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值