本文目录一览:
如何用java执行命令行
Java运行命令行并获取返回值,下面以简单的Java执行ping命令(ping 127.0.0.1 -t
)为例,代码如下:
Process p = Runtime.getRuntime().exec("ping 127.0.0.1 -t");
Process p = Runtime.getRuntime().exec("javac");
InputStream is = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while((line = reader.readLine())!= null){
System.out.println(line);
}
p.waitFor();
is.close();
reader.close();
p.destroy();
}
java中如何执行命令行语句
可以使用java.lang.Process和java.lang.Runtime实现,下面展示两个例子,其它用法请查阅资料:
1、执行ping命令:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ProcessTest {
public static void main(String[] args) {
BufferedReader br = null;
try {
String cmd = "ping 127.0.0.1";
// 执行dos命令并获取输出结果
Process proc = Runtime.getRuntime().exec(cmd);
br = new BufferedReader(new InputStreamReader(proc.getInputStream(), "GBK"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
proc.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
2、打开浏览器并跳转到百度首页:
import java.io.IOException;
public class ProcessTest {
public static void main(String[] args) {
try {
String exeFullPathName = "C:/Program Files/Internet Explorer/IEXPLORE.EXE";
String message = "";
String[] cmd = {exeFullPathName, message};
Process proc = Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Android-java怎么调用命令行的命令
Android-java调用命令行的命令可以使用Runtime类实现。 比如定义执行命令的方法: public void execCommand(String command) throws IOException { Runtime runtime = Runtime.getRuntime(); //申明runtime Process proc = runtime.exec(command.