Exécuter commande système sous Windows en Java
Bonsoir, je cherche à faire une classe pouvant lancer des programmes divers (.py .exe etc etc).
J'ai d'abord voulu tester une simple commande batch.
A savoir la commande help du cmd.
A l'exécution voilà ce que j'obtiens:
Citation:
Exécution de la commande:
Microsoft Windows [version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. Tous droits r‚serv‚s.
Je retourne donc une erreur.
Mais d'où vient elle je n'arrive pas à savoir...
Voici le code complet
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
//Allow to launch any system command
public class Launch {
private static BufferedReader getOutput(Process p) {
return new BufferedReader(new InputStreamReader(p.getInputStream()));
}
private static BufferedReader getError(Process p) {
return new BufferedReader(new InputStreamReader(p.getErrorStream()));
}
private String command;
public String getCommand(){
return this.command;
}
public Launch(String com){
this.command=com;
}
//launch command using exec
public void exe(){
try {
String[] commande = {"cmd.exe",this.getCommand()};
System.out.println("Exécution de la commande:\n");
Process p = Runtime.getRuntime().exec(commande);
BufferedReader output = getOutput(p);
BufferedReader error = getError(p);
String ligne = "";
while ((ligne = output.readLine()) != null) {
System.out.println(ligne);
}
System.out.println("En attente1:\n");
while ((ligne = error.readLine()) != null) {
System.out.println(ligne);
}
System.out.println("En attente2:\n");
p.waitFor();
System.out.println("Commande exécuté\n");
} catch (IOException e) {
System.out.println("La commande a échoué\n");
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("Echec wait for\n");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
String com="help";
Launch test=new Launch(com);
test.exe();
}
} |
En attente1 ne s'affiche pas, l'erreur est donc sur output.
Merci à vous !