版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mx_windxiao/article/details/77528295
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
/**
* 调用命令提示符命令并获取返回结果
* 并首先返回含有指定字符的一行
* 并解决中文操作系统代码
* @author
*
*/
public class TestCMD {
public static void main(String[] args) throws UnsupportedEncodingException {
String command = "ping 114.114.114.114";
String s = "数据包";
String line = null;
StringBuilder sb = new StringBuilder();
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec(command);
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")));
while ((line = bufferedReader.readLine()) != null) {
sb.append(line + "\n");
//System.out.println(line); //可在此处输出,则可不用装入StringBuilder
if (line.contains(s)) {
System.out.println(line);
System.out.println("----------------------------------------");
}
}
} catch (IOException e) {
e.printStackTrace();
}
String newStr = new String(sb.toString());
System.out.println(newStr);
}
}
-----------------------
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.SequenceInputStream;
/**
* 方法二
* @author
*
*/
public class TestCMD2 {
public static void main(String[] args) {
try {
Process process = Runtime.getRuntime().exec("cmd");
SequenceInputStream sis = new SequenceInputStream(process.getInputStream(), process.getErrorStream());
InputStreamReader isr = new InputStreamReader(sis, "gbk");
BufferedReader br = new BufferedReader(isr);
// next command
OutputStreamWriter osw = new OutputStreamWriter(process.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
bw.write("ping 114.114.114.114");
bw.newLine();
bw.flush();
bw.close();
osw.close();
// read
String line = null;
while (null != (line = br.readLine())) {
System.out.println(line);
}
process.destroy();
br.close();
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}