之前查询了java去引用python代码的方法,因为python中使用了第三方库,选择使用
Runtime.getRuntime().exec()
这个方法体,但是还是一直报错说java代码没有对应的.dll文件,之前草率的把.dll文件直接复制到java文件下,还是不对,查询网络发现因为java和python运行代码的机制不同,最后发现需要单独引入对应.dll的文件所在路径,现已完美解决,代码展示如下:
public class javaPython {
public static void main(String[] args) throws Exception{
try {
Process proc = Runtime.getRuntime().exec("python D:\\finally02.py",null,new File("D:\\USBCAN-I"));// 执行py文件以及dll所在的地址
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader error = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
System.out.println("Python gram out");
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
//此处是为了看代码报错原因
System.out.println("Python gram error");
while ((line = error.readLine()) != null) {
System.out.println(line);
}
in.close();
proc.waitFor();
System.out.println(proc.waitFor());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}