1. 程式人生 > >java呼叫命令提示符並返回結果(中文無亂碼)

java呼叫命令提示符並返回結果(中文無亂碼)


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();
		}
	}
}