shell子进程中默认继承当前环境的环境变量。当不需要父进程的环境变量时,使用一下代码:
public static List<String> exe(String cmds, boolean fromParentEnv)
throws IOException, InterruptedException {
List<String> res = Lists.newArrayList();
Process processTask=null;
BufferedReader br = null;
BufferedReader er = null;
try {
ProcessBuilder processBuilder = new ProcessBuilder("sh", "-c", cmds);
if(!fromParentEnv) {
Map<String, String> env = processBuilder.environment();
env.clear();
env.put("LANG", "en_US.UTF-8"); //must set LANG to support chinese
}
processTask = processBuilder.start();
int result = processTask.waitFor();
br = new BufferedReader(new InputStreamReader(processTask.getInputStream()));
er = new BufferedReader(new InputStreamReader(processTask.getErrorStream()));
String line;
while((line = br.readLine()) != null) {
res.add(line);
}
while((line = er.readLine()) != null) {
res.add(line);
System.err.println("Shell Script Error: " + line);
}
return res;
} catch (IOException | InterruptedException e) {
e.printStackTrace();
return res;
} finally {
if(br != null) {
br.close();
}
if(er != null) {
er.close();
}
if(processTask != null) {
processTask.destroy();
}
}
}
上述env.clear()清除环境变量,这时子shell中出现乱码。需要手动设置环境变量:
env.put("LANG", "en_US.UTF-8"); //must set LANG to support chinese
即可解决问题。