I am trying to figure out how to pass parameter and command to the command prompt via Java.
I am trying to create a program which gel serveral command prompt application together.
I have tried using
Process p = Runtime.getRuntime().exec()
but i can only execute one command at a time how do i pass parameters ?
Thanks.
Please read the source code of Runtime.Class.
There are several optional functions could be used like
public Process exec(String cmdarray[]) throws IOException {
return exec(cmdarray, null, null);
}
You could put commands in an array as the parameter of the function.
Hope it would be helpful for you.
Related
I was successfully using AutoIt to execute commands but I was thinking I could get a more stable implementation via Runtime. That way I know the commands will always be executed and won't get thrown by Interruption exceptions, and other random crap. Is there something about Runtime that I don't know which won't allow for continuous execution of commands? Does it not have a memory for the outputs of previous commands, i.e. is it not running in a persistent command line?
The following commands navigate to a folder and execute a Maven script. How would I get this to work? If there were 10+ more commands that follow, would they execute within in the same process?
sendCommand("cmd.exe cd homepath/plugins");
sendCommand("mvn archetype:generate -DarchetypeCatalog=file://homepath/.m2/repository");
private static void sendCommand(String text) throws IOException {
Runtime.getRuntime().exec(text);
}
Runtime.exec() returns a Process instance. Call waitFor() on this object to wait until it is complete before running a next command. You can communicate with a Process via its getInputStream()/getOutputStream() methods.
Also read the Javadoc. For Runtime.exec it says "Executes the specified string command in a separate process."
A few things.
You should use Process and ProcessBuilder instead.
The commands have to be split up and tokenized according to arguments.
The way you have it written, those two commands will not be executed in the same process.
Fortunately for you, ProcessBuilder supports changing the working directory of the command anyway.
As an example:
sendCommand("homepath/plugins", "mvn", "archetype:generate", "-DarchetypeCatalog=file://homepath/.m2/repository");
private static void sendCommand(String workingDirectory, String... command) throws IOException {
Process proc = new ProcessBuilder(command).directory(new File(workingDirectory)).start();
int status = proc.waitFor();
if (status != 0) {
// Handle non-zero exit code, which means the command failed
}
}
Notice how a) the command has been split up, and b) that the working directory is passed in and set using ProcessBuilder.directory(File). This will get your desired behavior, but note that each command will still be a separate process, and there's no way to combine them with Java. You'd have to use Maven's features to get them all to run at once by specifying multiple build targets.
I'm new with JCommander and I'm trying to use it in my JAVA Command Line Application.
Fisrt thing I did is I've created my CommandLineArguments class.
Now, I'm trying to print options given with arguments in command line. But I think I'm missing something.
Here is my main class :
public static void main(String[] args) {
String[] argv={"-h","host"};
CommandLineArguments arguments=new CommandLineArguments();
JCommander commands= new JCommander(arguments);
try {
commands.parse(argv);
System.out.println(commands.getParsedCommand());
} catch (Exception e) {
System.out.println(e.getMessage());
commands.usage();
}
}
Once I run this class, I got : null as output. Seems like getParsedCommand() is not used as it should.
Can someone tell me how to use JCOmmmander methods correctly so I can see options given with arguments?
What I'm trying to do here is, once the user runs java -jar myApp.jar -port portNumber -h hostname -d database -c collection I wanna be able to get portNumber hostname database and collection value so I can establish a connexion and send queries.
Hope I was clear enough.
Ismail
You need to make a distinction between commands and parameters. In the example you give, you only need parameters.
The first chapter of the JCommander documentation provides a clear enough example of how to handle parameters. If your CommandLineArguments class is annotated as in the example, the parameter values should be correctly set in that class after calling parse(argv).
Commands are explained in a later chapter dealing with more complex command-line syntaxes.
So I'm creating a Java program and I want to make it so that you can ask it to open a program.
But, here's the catch, I want the program it opens to be taken from the user input, right now I'm trying to change this
try{Process p = Runtime.getRuntime().exec("notepad.exe");}
catch(Exception e1){}
Into something that opens a program that you asked it to open.
Here's an example of what I want:
User: Can you open chrome?
Program: Of course, here you go!
chrome opens
Could anyone tell me how I would be able to do this?
You can do it in two ways:
1.By Using Runtime:
Runtime.getRuntime().exec(...)
So, for example, on Windows,
Runtime.getRuntime().exec("C:\application.exe -arg1 -arg2");
2.By Using ProcessBuilder:
ProcessBuilder b = new ProcessBuilder("C:\application.exe", "-arg1", "-arg2");
or alternatively
List<String> params = java.util.Arrays.asList("C:\application.exe", "-arg1", "-arg2");
ProcessBuilder b = new ProcessBuilder(params);
or
ProcessBuilder b = new ProcessBuilder("C:\application.exe -arg1 -arg2");
The difference between the two is :
Runtime.getRuntime().exec(...)
takes a single string and passes it directly to a shell or cmd.exe process. The ProcessBuilder constructors, on the other hand, take a varargs array of strings or a List of strings, where each string in the array or list is assumed to be an individual argument.
So,Runtime.getRuntime.exec() will pass the line C:\application.exe -arg1 -arg2 to cmd.exe, which runs a application.exe program with the two given arguments. However, ProcessBuilder method will fail, unless there happens to be a program whose name is application.exe -arg1 -arg2 in C:.
You can try it with like. Pass whole path of where you install chrome.
try{
Process p = Runtime.getRuntime().exec("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe");
}
catch(Exception e1){
}
When using exec, it is essentially the same as if you were using the command line on windows. Open Command Prompt, type open, and see if it gives details as to how it opens files. If not, find the opener. Usually when dealing with command line operations, there are multiple parameters that are required for opening files/applications. An example of this would be for opening the "TextEdit.app" application on a mac.
Process p = Runtime.getRuntime().exec("open -a TextEdit.app");
Terminal(for mac) would open the app using the -a flag, meaning "application." You could open a file doing:
Process p = Runtime.getRuntime().exec("open filename.file_ext -a TextEdit.app");
The second one will tell the computer to find the application named <app_name>.app and open the file filename.file_ext
I know this is not going to work for a windows machine, but it's only to show how to use the command line operations for opening files and applications. It should be similar for windows though.
Hope this helps
I know that by using the command in the terminal
date --set="2011-12-07 01:20:15.962"
you would actually be able to change the System clock, so I tried it in Java and came up with the following statement
Process p = Runtime.getRuntime().exec("date --set=\"2011-12-07 01:20:15.962\"");
but it was not able to set the clock.
Do you have any idea guys how it may be able work?
Premise:
The machine is Slackware,
The privilege is root level
There are two problems with this line of code:
Process p = Runtime.getRuntime().exec("date --set=\"2011-12-07 01:20:15.962\"");
You did not wait for the process to complete (see also http://docs.oracle.com/javase/6/docs/api/java/lang/Process.html#waitFor())
Parameters should be separated from program name, try this:
"date", "-s", "2011-12-07 01:20:15.962"
Alternatively, invoke shell as the process, and pass in a line of code:
.exec("sh", "-c", "date --set=\"2011-12-07 01:20:15.962\"")
Process p=Runtime.getRuntime().exec(new String[]{"date","--set","2011-12-07 01:20:15.962"});
The above statement worked like magic. #Howard Gou was right with "Parameters should be separated from program name"
The parts of the command statement should be passed by using a String array.
void restartWeb() {
try {
String[] command = new String[] {"webRestarter.exe" , ">>","webLog.log"};
Runtime.getRuntime().exec(command);
} catch (java.io.IOException err) {
webServer.logError(err.getMessage());
}
}
Why doesn't this work? How could I fix it so it does work like I want it to?
-- Executes webRestarter.exe with parameters >>webLog.log
So it'd spit out something like this:
webRestarter.exe>>webLog.log
You simply can't use pipes in a exec call. Pipes are a functionality of the shell and not of the operating system. So we have to call the shell executable and pass the command. Try this instead:
String[] command = new String[] {"cmd.exe", "/c", "start webRestarter.exe", ">>","webLog.log"};
Parameters are passed directly to the webRestarter.exe command. You can't use parameters to redirect standard output to a file, as this is usually done by your command line interpreter.
However, the exec() method returns a Process object, which you could use to retrieve standard output and write it to a file.
Sources:
http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html#exec%28java.lang.String%29
http://download.oracle.com/javase/6/docs/api/java/lang/Process.html
If I'm not mistaken, pipes, redirects etc are a function of a shell. In this context, these are just arguments. You could handle this as simply as using cmd.exe with a /c switch as part of your command, I believe it'll handle this correctly, or handle the standard input/output yourself (though that's notoriously fraught with problems, I prefer something like commons-exec).
Just thought I'd mention two things that might be handy for working with Processes.
ProcessBuilder
is a good way to obtain a Process (in
code intended to run in a 1.5+ JRE).
It is recommended to carefully
read and implement all the
recommendations of When
Runtime.exec() won't.