解决java调用python脚本出现乱码的问题

解决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

希望本文对大家有帮助

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值