本文目錄一覽:
如何用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.
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/239665.html