java调用windows Bat或者Linux Shell,并获取执行中的输出(解决了字符乱码问题)
String strCmd = "dir"; // bat
//String strCmd = "ls"; // shell
Process process;
BufferedReader input;
try {
if (SYstem.getProperties().getProperty("os.name").matches("Windows.*$")){
process = Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c", strCmd}); //bat
process.waitFor();
input = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")));
} else {
process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", strCmd}); //shell
process.waitFor();
input = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("UTF-8")));
}
String line = "";
while((line = input..readLine()) != null){
System.out.println(line);
}
input.close();
} catch (IOException e) {
e.printStackTrace();
}