您的位置:首页 > 运维架构 > Shell

java调用Bat cmd命令和Linux Shell,并获取执行中的输出(字符乱码问题解决)

2019-01-16 09:53 2191 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/betteronly/article/details/86502362

  java调用windows Bat或者Linux Shell,并获取执行中的输出(解决了字符乱码问题)

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

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐