java runtime的用法来调用系统

tech2023-09-30  93

Process :Process类是一个抽象类,其内部所有的方法都是抽象的,Runtime.exec()方法可以创建一个本地进程,并返回Process子类的一个实例。

Rumtime:提供了和系统交互的入口

通过runtime来调用cmd来调用dir。

package com.mtlk.wd; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; public class RuntimeDemo { public static void main(String[] args) throws IOException{ Process pro = Runtime.getRuntime().exec("cmd /k dir"); InputStream in = pro.getInputStream(); Scanner sc = new Scanner(in); while(sc.hasNextLine()) { System.out.println(sc.nextLine()); } } }

String版用法

package com.mtlk.wd; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; public class RuntimeDemo2 { public static void main(String[] args) throws IOException{ Process pro = Runtime.getRuntime().exec(new String[] {"cmd","/k","dir"}); InputStream in = pro.getInputStream(); Scanner sc = new Scanner(in); while(sc.hasNextLine()) { System.out.println(sc.nextLine()); } } }
最新回复(0)