java在windows下执行dos命令,及返回执行结果,在CH win系统下,返回GBK格式的字节数据。
package com.regedit;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class WindowsCommandUtil {
/**
* @Description do windows command
* @Param command
* @return GBK resulet byte[]
**/
public static final byte[] doCommand(String command) throws Exception{
Process process = Runtime.getRuntime().exec(command);
WindowsRegistry.StreamReader reader = new WindowsRegistry.StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
return reader.getResult();
}
static class StreamReader extends Thread {
private InputStream is;
private byte[] bytes;
public StreamReader(InputStream is) {
this.is = is;
}
@Override
public void run() {
try {
bytes = toByteArray(is);
} catch ( IOException e) {
e.printStackTrace();
}
}
public byte[] getResult() {
return bytes;
}
}
private static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024*4];
int n;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
}