解决java调用python脚本出现乱码的问题
业务场景:通过java代码调用python脚本
问题:java启动python脚本乱码
解决方案
将读取的数据的编码格式为:“GBK”(测试成功),“GB2312”
package cn.com.jrsoft.test.pythontest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class ExecutePython {
public static void main(String[] args) {
try {
// 设置 Python 解释器和脚本路径
String pythonInterpreterPath = "D:\\python\\Environment\\python.exe"; // 替换为您的Python解释器路径
String pythonScriptPath = "D:\\python\\code\\test\\pythonProject2\\source\\inputZwThsis.py"; // Python脚本路径
// 设置命令行参数
String[] args1 = new String[]{pythonInterpreterPath, pythonScriptPath};
// 使用ProcessBuilder来执行命令
ProcessBuilder pb = new ProcessBuilder(args1);
pb.directory(new java.io.File("D:\\python\\code\\test\\pythonProject2\\source")); // 设置工作目录
// 启动Python脚本
Process pr = pb.start();
// 读取标准输出
BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream(), "GBK"));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
// 读取错误输出
BufferedReader errorReader = new BufferedReader(new InputStreamReader(pr.getErrorStream(), "UTF-8"));
while ((line = errorReader.readLine()) != null) {
System.err.println("Error: " + line);
}
errorReader.close();
// 等待进程完成
pr.waitFor();
System.out.println("Python 脚本执行完成,退出代码:" + pr.exitValue());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
问题出现的原因:
utf-8是国际通用的编码,windows操作系统的默认编码方式为GBK
希望本文对大家有帮助