最近在做一个案例需要用java调用cmd执行python文件,但在获取返回结果的时候,中文出现了乱码。
代码及输出结果如下:

public static String predictPython(String path, String param) throws IOException, InterruptedException {
		String exe = "python";
		String command = path+"WEB-INF\\classes\\python\\faceRecognition.py";
		String[] cmdArr = new String[] { exe, command, param, path+"WEB-INF\\classes\\python\\" };
		System.out.println( exe + " " + command + " " + param + " " + path+"WEB-INF\\classes\\python\\" );
		Process process = Runtime.getRuntime().exec(cmdArr);
		BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
		String pythonResult = "";
		String line;
		while ((line = in.readLine()) != null) {
			pythonResult = line;
			System.out.println("cmd返回结果:" + line);
		}
		in.close();
		int result = process.waitFor();
		System.out.println("执行结果:" + result);
		return pythonResult;
	}

输出结果:

java 执行 cmd命令 java执行cmd命令带中文_返回结果

解决方案:

只需要改一处地方,在实例化InputStreamReader的时候指定字符为GBK,更改后:

java 执行 cmd命令 java执行cmd命令带中文_返回结果_02


更改后的结果:

java 执行 cmd命令 java执行cmd命令带中文_返回结果_03