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);
}