大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
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();
}
public static void main(String[] args) throws IOException, InterruptedException {
// 执行ping命令
String cmdPing = "ping 127.0.0.1";
Runtime run = Runtime.getRuntime();
Process process = run.exec(cmdPing);
process.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
try {
Process p = rt.exec("cmd /c ping -t");
InputStream is = p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String temp = null;
while((temp =br.readLine()) != null){
System.out.println(temp);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
你应该看看api process 返回的是流,按照输出流的方法操作即可.公司上不去外网,有代理才行,所以没有ping 百度,ping的本机.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class CallCmd {
public static void main(String[] args) {
BufferedReader br = null;
try {
Process p = Runtime.getRuntime().exec("ping 127.0.0.1");
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
StringBuilder sb=new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
String line = null;
while((line = br.readLine()) != null){
System.out.println(line);
}