Ich wollte eine .cmd-Datei von Java ausführen. Ich habe etwas, was für mich funktioniert. Kann mir jemand helfen, mögliche Fehler meines Programms zu verstehen?Ausführen einer .bat/.cmd-Datei von Java
import java.io.IOException;
/*
How to run a batch .bat or .cmd file from Java?
1. I don't want the command window to open up. It should be in background.
2. Gracefully destroy any new process created.
3. Need to confirm the quality of the program with experts.
*/
public class RunBat {
public static void main(String args[]) {
Runtime run = Runtime.getRuntime();
//The best possible I found is to construct a command which you want to execute
//as a string and use that in exec. If the batch file takes command line arguments
//the command can be constructed a array of strings and pass the array as input to
//the exec method. The command can also be passed externally as input to the method.
Process p = null;
String cmd = "D:\\Database\\TableToCSV.cmd";
try {
p = run.exec(cmd);
p.getErrorStream();
System.out.println("RUN.COMPLETED.SUCCESSFULLY");
}
catch (IOException e) {
e.printStackTrace();
System.out.println("ERROR.RUNNING.CMD");
p.destroy();
}
}
}
Ist meine Lösung zuverlässig? Wie kann ich sicherstellen, dass, sobald die .cmd ausgeführt wird, keine Prozesse hängen bleiben.
Danke.
Ich dachte, ich die Fehler sammeln kann, wenn eine von p.getErrorStream(), das habe ich nicht vervollständigen Teil des Codes. p.waitFor(), ah, mein Schlechter, dies ist eines der Dinge, die ich wollte, um zu wissen, ob der Prozess abgeschlossen ist, Ergebnis der nicht die Java Doc. Ich werde einen finally-Block für p.destroy() erstellen. Danke für Ihre Zeit. – dRv
Ihr Kommentar deutet darauf hin, dass meine Antwort zufriedenstellend ist. Kannst du es als Antwort akzeptieren? – YoK