java调用控制台执行命令

xiaoxiao2021-02-28  41

Runtime类百度百科解释

1.用于内存管理

2.用于执行其他程序

在安全的环境中,可以在多任务操作系统中使用Java去执行其他特别大的进程(也就是程序)。exec()方法有几种形式命名想要运行的程序和它的输入参数。exec()方法返回一个Process对象,可以使用这个对象控制Java程序与新运行的进程进行交互。exec()方法本质是依赖于环境。 下面的例子是使用exec()方法启动windows的记事本notepad。这个例子必须在Windows操作系统上运行。 class ExecDemo { public static void main(String args[]){ Runtime r = Runtime.getRuntime(); Process p = null; try{ p = r.exec(“notepad”); } catch (Exception e) { System.out.println(“Error executing notepad.”); } } } exec()还有其他几种形式,例子中演示的是最常用的一种。exec()方法返回Process对象后,在新程序开始运行后就可以使用Process的方法了。可以用destory()方法杀死子进程,也可以使用waitFor()方法等待程序直到子程序结束,exitValue()方法返回子进程结束时返回的值。如果没有错误,将返回0,否则返回非0。下面是关于exec()方法的例子的改进版本。例子被修改为等待,直到运行的进程退出: class ExecDemoFini { public static void main(String args[]){ Runtime r = Runtime.getRuntime(); Process p = null; try{ p = r.exec(“notepad”); p.waitFor(); } catch (Exception e) { System.out.println(“Error executing notepad.”); } System.out.println(“Notepad returned ” + p.exitValue()); } } 下面是运行的结果(当关闭记事本后,会接着运行程序,打印信息): Notepad returned 0 按任意键继续… 当子进程正在运行时,可以对标准输入输出进行读写。getOutputStream()方法和getInPutStream()方法返回对子进程的标准输入和输出。

得到执行命令后的结果

package cmd; import java.io.BufferedReader; import java.io.InputStreamReader; public class Test { public static void main(String[] args) { String cmd="ipconfig -all"; String s="IPv4"; String line = null; StringBuilder sb = new StringBuilder(); Runtime runtime = Runtime.getRuntime(); //得到本程序 try { Process process = runtime.exec(cmd); //该实例可用来控制进程并获得相关信息 //获取进程输出流 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((line = bufferedReader.readLine()) != null) { sb.append(line + "\n"); if (line.contains(s)) { System.out.println(line); } } } catch (Exception e) { e.printStackTrace(); } } }
转载请注明原文地址: https://www.6miu.com/read-72097.html

最新回复(0)