Ma solution préférée pour cela est de passer dans le répertoire que le Runtime
dans lequel le processus se déroulera. Je créerais une petite méthode comme suit : -
public static String cmd(File dir, String command) {
System.out.println("> " + command); // better to use e.g. Slf4j
System.out.println();
try {
Process p = Runtime.getRuntime().exec(command, null, dir);
String result = IOUtils.toString(p.getInputStream(), Charset.defaultCharset());
String error = IOUtils.toString(p.getErrorStream(), Charset.defaultCharset());
if (error != null && !error.isEmpty()) { // throw exception if error stream
throw new RuntimeException(error);
}
System.out.println(result); // better to use e.g. Slf4j
return result; // return result for optional additional processing
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Notez que cela utilise le Bibliothèque Apache Commons IO c'est-à-dire ajouter à pom.xml
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.10.0</version>
</dependency>
Pour utiliser le cmd
méthode, par exemple
public static void main(String[] args) throws Exception {
File dir = new File("/Users/bob/code/test-repo");
cmd(dir, "git status");
cmd(dir, "git pull");
}
Cela donnera quelque chose comme ceci : -
> git status
On branch main
Your branch is up to date with 'origin/master'.
nothing to commit, working tree clean
> git pull
Already up to date.
0 votes
Un moyen de s'en sortir était de démarrer un nouveau shell et d'y envoyer toutes vos commandes - webmasterworld.com/linux/3613813.htm