如何在java端调用python脚本

1.可以先将python脚本新建文件夹放在项目目录resource目录下

2.在java类中首先读取python脚本,在本地的话可以直接通过class.getResource()获取到脚本的绝对路径,但是在springboot项目打包成jar部署在服务器上之后就不好使了

3.所以可以先使用流读取到脚本的内容再copy一份到根目录下,再拿到路径去调用,调用完成之后再将生成的临时文件删除

/**

  • copy临时文件获取文件路径
  • */
    private String getFilesPath(){
    String filePath=“”;
    try{
    ClassPathResource classPathResource = new ClassPathResource(“pyfiles/xxx.py”);
    InputStream inputStream = classPathResource.getInputStream();
    byte[] bdata = FileCopyUtils.copyToByteArray(inputStream);
    //生成临时文件,这个是生成在根目录下
    filePath=System.getProperty(“user.dir”)+“xxx.py”;
    File file = new File(filePath);
    if(!file.exists()){
    file.createNewFile();
    }
    FileOutputStream fileOutputStream = new FileOutputStream(file);
    fileOutputStream.write(bdata);
    fileOutputStream.close();
    }catch (Exception e){
    e.printStackTrace();
    logger.info(“copy文件失败:”+e.getMessage());
    }
    return filePath;
    }

3.再获取到脚本路径之后,就可以使用java内置的Runtime方法去直接调用脚本

String [] para =new String[] {“python”,path};

/**

  • 调用py
  • */
    private String invokePy(String[] para) {
    StringBuilder result = new StringBuilder();
    try {
    Process process = Runtime.getRuntime().exec(para);
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(),“UTF-8”));
    String line;
    while ((line = reader.readLine()) != null) {
    result.append(line);
    }
    reader.close();
    process.destroy();
    } catch (Exception e) {
    e.printStackTrace();
    }
    return result.toString();
    }

4.调用成功,获取到结果之后就可以对结果转成json字符串解析

/**

  • 处理json数据
  • */
    private void getJson(String allResult) {
    JSONObject jsonObject = new JSONObject(allResult);
    }
    5.最后在处理完数据之后将临时文件删除
    File files = new File(path);
    if(files.exists()){
    boolean delete = files.delete();
    System.out.println(“删除临时文件:”+delete);
    }
  • 6
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一名软件修理工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值