Running Shell or System Command in JAVA
private void myFunction(String userName){
String fileName = this.generateFile(userName);
String[] command = new String[4];
command[0] = "cmd";
command[1] = "/C";
command[2] = "dir";
command[3] = "7za a "+ userName+".7z "+ fileName +" -p"+this.password;
try {
Process p = Ru开发者_C百科ntime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
ProcessBuilder proc = new ProcessBuilder(command[3]);
proc.start();
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
}
I tried both the way of running command line in JAVA. None of them worked. Can anyone enlighten me on what I am doing wrong. I tried for 3 hours but no luck :(
I keep getting this error File Not Found java.io.IOException: Cannot run program "command"
The same command when I run from cmd, it works. I am using Windows..
Please Help. Thank you!
Try this:
final Runtime rt = Runtime.getRuntime();
rt.exec(your command line here as a single String);
At the risk of repeating myself I'm gonna say it again: java.lang.ProcessBuilder
is much better option
Your command is not in any of the directories in the PATH variable. And it is likely not in the "current working directory" of your Java programms process. Either set PATH correctly, or give the full absolute path to the command which you want to run.
精彩评论