要在Java中执行Git命令,您可以使用Java的Runtime
类或ProcessBuilder
类
方法1:使用Runtime类
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
try {
String gitCommand = "git --version";
Process process = Runtime.getRuntime().exec(gitCommand);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
}
}
方法2:使用ProcessBuilder类
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
try {
String[] gitCommand = {"git", "--version"};
ProcessBuilder processBuilder = new ProcessBuilder(Arrays.asList(gitCommand));
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
}
}
这两个示例都会执行git --version
命令并打印输出结果。您可以根据需要修改gitCommand
数组来执行其他Git命令。请注意,这些示例假设您的系统已经安装了Git并将其添加到了环境变量中。如果尚未安装,您需要先安装Git。