I am having a hard time figuring out how to pass command line options through Java.
My Java code needs to call a binary file which in turn runs some instructions.
The command I need to pass is
./program 100 -r 1
Now there is no way can pass the option -r 1.
In my Java code, if I run:
command=new String [2];
command[0] = ".//program";
command[1] = " "+String.valueOf(nScen);
Process p = Runtime.getRuntime().exec(command);
everything works fine, and program is run correctly. nScen is an integer.
However, if I try
command=new String [3];
command[0] = ".//program";
command[1] = " "+String.valueOf(nScen);
command[2] = " -r 1";
Process p = Runtime.getRuntime().exec(command);
or
command=new String [2];
command[0] = ".//program";
command[1] = " "+String.valueOf(nScen)+" -r 1";
Process p = Runtime.getRuntime().exec(command);
program does not run. I tried other things like using .concat instead of + to merge strings.
What is the correct way of doing this?
Thanks for the help.
You could do this:
Process proc = Runtime.getRuntime().exec("./program " + nScen + " -r 1");
int exitVal = proc.waitFor();
You'll also need to catch exceptions.
Related
Hey all I am trying to change directories and then run my command with parameters.
final String path = "\\Local// Apps\\IBM\\SDP\\scmtools\\eclipse";
final String command = "scm help";
final String dosCommand = "cmd /c \"" + path + "\"" + command;
final Process process = Runtime.getRuntime().exec(dosCommand);
final InputStream in = process.getInputStream();
int ch;
while((ch = in.read()) != -1) {
System.out.print((char)ch);
}
It runs without errors but outputs nothing. However, this is what shows up after it finishes:
<terminated, exit value: 0>C:\Local Apps\IBM\SDP\jdk\bin\javaw.exe (Jul 22, 2019, 11:21:37 AM)
The expected output should be:
So am I doing this correctly?
AS suggested by Andreas
Process p = null;
ProcessBuilder pb = new ProcessBuilder("scm.exe");
pb.directory(new File("C:/Local Apps/IBM/SDP/scmtools/eclipse"));
p = pb.start();
I get the following error:
Cannot run program "scm.exe" (in directory "C:\Local Apps\IBM\SDP\scmtools\eclipse"): CreateProcess error=2, The system cannot find the file specified
You should use ProcessBuilder instead of Runtime.exec, e.g.
Process proc = new ProcessBuilder("scm.exe", "help")
.directory(new File("C:\\Local Apps\\IBM\\SDP\\scmtools\\eclipse"))
.inheritIO()
.start();
proc.waitFor(); // optional
You can also go through the command interpreter if needed, e.g. if the command is a script (.bat or .cmd file):
Process proc = new ProcessBuilder("cmd", "/c", "scm", "help")
.directory(new File("C:\\Local Apps\\IBM\\SDP\\scmtools\\eclipse"))
.inheritIO()
.start();
proc.waitFor();
The inheritIO() means that you don't need to process the commands output. It will be sent to the console, or wherever Java's own output would go.
I'm trying to get the output of grep linux shell command in java by using process builder. But i got a stuck in this case. Please help me.
Thank in advice!
String[] args = new String[7];
args[0] = "/bin/bash";
args[1] = "-c";
args[2] = "grep";
args[3] = "-n";
args[4] = "-e";
args[5] = "KERNELVERSION";
args[6] = kernelFilePath.trim();
ProcessBuilder pb;
Process process = null;
try {
pb = new ProcessBuilder(args);
pb = pb.directory(new File(directory));
pb.inheritIO();
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
process = pb.start();
process.waitFor();
} catch (IOException | InterruptedException e) {
System.out.println("executeCmdWithOutput() exception : " + e.toString());
} finally {
if (process != null) {
process.destroy();
}
}
==> Error:
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.
I tried the command in bash and it worked fine:
grep -n -e KERNELVERSION ..../Makefile
Have you tried change the args[2] as full command?
Also, you can use pgrep, it does not require you to use pipe.
You don't need to explicitly run /bin/bash in order to execute the grep process. Just call it directly and ProcessBuilder will run it:
String[] args = {"grep", "-n", "KERNELVERSION", kernelFilePath.trim()};
Also, you don't need to use the -e option, unless there are multiple patterns that you are searching for.
If you really wanted to run grep in /bin/bash:
String[] args = {"/bin/bash", "-c", "grep -n KERNELVERSION " + kernelFilePath.trim()};
passes a single argument to bash containing the full command and arguments to execute.
I use java to excute a command line to create a database, i get an error when i excute this piece of code:
private final String POSTGRES_PATH = "\"C:\\Program Files\\PostgreSQL\\9.3\\bin\\psql.exe\"";
private final String DATA_BASE = "bd_name";
private void creerDataBase() {
String command = this.POSTGRES_PATH + " -U postgres -d postgres -c \"CREATE DATABASE " + this.DATA_BASE + "\"";
System.out.println("command = " + command);
String creerBDD = executerCommande(command);
System.out.println("Resultat : " + creerBDD);
}
public String executerCommande(String command) {
String line;
String resultat = "";
try {
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", command);
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
while (true) {
line = r.readLine();
if (line == null) {
break;
}
resultat += line + "\n";
}
} catch (Exception e) {
System.out.println("Exception = " + e.getMessage());
}
return resultat;
}
I get this result:
command = "C:\Program Files PostgreSQL\9.3\bin\psql.exe"\ -U postgres -d postgres -c "CREATE DATABASE bd_name"
and this error:
'C:\Program' n'est pas reconnu en tant que commande interne
This mean that Program is not an intern command.
but when i excute this command in CMD it work fine?
Is there any way to Build this Path because the ProcessBuilder not recognize C:\Program Files
Thanks for #Aaron his idea helps me so i solved this problem using this:
private final String POSTGRES_PATH = "C:\\PROGRA~1\\PostgreSQL\\9.3\\bin\\psql.exe";
this C:\\PROGRA~1 inteed of this: C:\\Program Files
A possible solution would be to remove the path (with spaces) from your constant field and use the directory method:
Sets this process builder's working directory. Subprocesses subsequently started by this object's start() method will use this as their working directory. The argument may be null -- this means to use the working directory of the current Java process, usually the directory named by the system property user.dir, as the working directory of the child process.
Changing your code to:
private final String POSTGRES_DIR = "C:\\Program Files\\PostgreSQL\\9.3\\bin\\"
private final String POSTGRES_COMMAND = "psql.exe";
....
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", command).directory(new File(POSTGRES_DIR));
.....
Don't run cmd.exe if you want to run a separate binary program.
cmd.exe is for scripts like *.cmd or *.bat
With cmd.exe you have to pass your command as an argument of CMD, and you should manage all OS-specific pitfalls like long paths with whitespaces, quotes inside qoutes etc.
Instead, you had better run psql itself.
The ProcessBuilder takes a command and all the arguments as a list of separate strings. And ProcessBuilder is clever enough to do all the necessary magic with quotes and whitespaces by itself.
And take attention to the list of arguments - shells separate arguments by whitespaces, while psql might recognize the sequence of strings as a single argument.
We may assume that -U postgress is a single argument for psql, but for shell (cmd.exe in our case) these are two separate arguments - -U and postgress, so we should pass them to the ProcessBuilder separately
So the better way to run psql is to run it directly, something like that:
new ProcessBuilder("C:\\Program Files\\PostgreSQL\\9.3\\bin\\psql.exe",
"-U", "postgres",
"-d", "postgres",
"-c", "\"CREATE DATABASE " + this.DATA_BASE + "\"");
What you could try is instead of the space between program and files is %20 or \s.
So like:
command = "C:\\Program%20Files\\PostgreSQL\\9.3\\bin\\psql.exe"
or
command = "C:\\Program\sFiles\\PostgreSQL\\9.3\\bin\\psql.exe"
I hope one of them works for you, please let me know
EDIT: use double \ to get it to recognize the \
I am using this command line argument to clone a database :-
"C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqldump" -u root -ppass -d oldDB | mysql -u root -ppass -DnewDB
This piece works fine when directly pasted into command line. But, when I tried running this argument using java, it did not work. My java code is :-
String serverLoc = "C:\\Program Files\\MySQL\\MySQL Server 5.6\\";
String a = "\"" + serverLoc + "bin\\mysqldump\" " ;
String cmd = a + "-u root -ppass -d oldDB | mysql -u root -ppass -DnewDB";
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("SUCCESS");
} else {
System.out.println("ERROR");
}
//OUTPUT : ERROR
Exception handling not shown as no stack trace is printed. When I print cmd, the above desired string is printed which works when pasted into command line. Please help me solve this dilemma.
I believe on windows you have to call the command this way:
Runtime.getRuntime().exec("cmd " + ecuteCmd)
Also I think it is better to use Runtime.getRuntime().exec(String[]) method
String prog = "C:\\program files\\server\\xampp\\mysql\\bin\\mysql";
String user = "-uroot";
String pass = "-ppass";
Process runtimeProcess = Runtime.getRuntime().exec(new String[] { prog, user, pass });
The modern way by using ProcessBuilder: thx #Daniel
String prog = "C:\\program files\\server\\xampp\\mysql\\bin\\mysql";
String user = "-uroot";
String pass = "-ppass";
ProcessBuilder builder = new ProcessBuilder(prog, user, pass);
Process runtimeProcess = builder.start();
int result = runtimeProcess.waitFor();
//...
I am struggling with ProcessBuilder folks! I want to run the utility 'nativetoascii' in. I can run it on the command line and also via Runtime.exec() with no problems.
My code is:
'
String command = "\"C:\\Program Files (x86)\\Java\\jdk1.6.0_32\\bin\\native2ascii\"";
String encoding = " -encoding ";
String utf8 = "UTF8 ";
String inputFile = "C:\\Users\\joe\\Desktop\\resources\\encoding\\orig.properties ";
String outputFile ="C:\\Users\\joe\\Desktop\\resources\\encoding\\convertedViaProcessBuilder.properties";
List<String> commandArgs = new ArrayList<String>();
commandArgs.add(command);
commandArgs.add(encoding);
commandArgs.add(utf8);
commandArgs.add(inputFile);
commandArgs.add(outputFile);
ProcessBuilder builder = new ProcessBuilder(commandArgs);
Process p = builder.start();
p.waitFor();
I have also written code to read the output from the process and it says:
Usage: native2ascii [-reverse] [-encoding encoding] [inputfile [outputfile]]
Clearly I'm doing something wrong with the command and its arguments. Can anyone tell me what I'm doing wrong? Thanks.
Your second argument is " -encoding " which it would be "-encoding" Spaces matter when you run a command. ;)