在Java中調用Python腳本有多種方法,下面介紹兩種常用的方法:
ProcessBuilder
類:import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
ProcessBuilder pb = new ProcessBuilder("python", "path/to/your/python/script.py");
Process process = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode;
try {
exitCode = process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Python script exited with code: " + exitCode);
}
}
這種方法通過創建一個ProcessBuilder
對象來執行Python腳本,并讀取Python腳本輸出的結果。可以使用ProcessBuilder
的start()
方法來啟動Python腳本,并使用getInputStream()
方法獲取腳本輸出的結果。
Runtime
類:import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
String command = "python path/to/your/python/script.py";
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode;
try {
exitCode = process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Python script exited with code: " + exitCode);
}
}
這種方法通過調用Runtime
類的exec()
方法來執行Python腳本,并讀取Python腳本輸出的結果。可以將要執行的Python命令傳遞給exec()
方法,并使用getInputStream()
方法獲取腳本輸出的結果。
無論使用哪種方法,都可以通過讀取Python腳本的輸出來獲取結果,并可以使用waitFor()
方法等待腳本執行完畢,獲取腳本的退出碼。