commandline call from java - java

I'm looking to call the command line from a java program. I have successfully entered the command line using this bit of code
String[] cmd = new String[2];
cmd[0] = "cmd /c dir";
Runtime rt = Runtime.getRuntime();
System.out.println("Execing " + cmd[0]);
Process proc = rt.exec(cmd[0]);
However, the actual commands aren't working. I am not too familiar with command line, I have only ever typed directly into it. So my question is how do I pass multiple arguments in? For instance if I wanted to change to C:\ I would have thought I could just add cd\ on the end but this doesn't seem to work?
Thanks in advance

use the & symbol. Everything needs to go in at once. For instance: cd .. & echo "test" will go to the previous directory and then echo test.
Taken from here: http://forums.techguy.org/dos-other/697113-solved-multiple-commands-cmd.html

Related

Execute external program from Java (with cmd, Windows)

I've done many research for executing an external program (e.g. iTunes) by some simple code, however the suggestions did never work. Sometimes nothing happend, sometimes I got this error message:
English: Unable to find "Discord". Be sure the name is written correctly and try again.
My Code is the following:
try {
String name = (String) "start " + table.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
ProcessBuilder p = new ProcessBuilder("cmd.exe", "cd /D %HOMEDRIVE%%HOMEPATH%/Desktop", "/c", name);
p.start();
} catch (Exception e) {
e.printStackTrace();
}
In my example I get the name of the external program from a JTable, this part is working fine. The ProcessBuilder is changing the directory to the desktop first. Then the external program should be executed by the start <program name> command. With this code I get the mentioned error message.
If you have a solution with cmd, please include changing the directory to the desktop.
You should pass each argument as a single entry to ProcessBuilder. In your current code, you sometimes take multiple arguments together (like cd /D %HOME...). Try passing every argument as it's own parameter, including the command to start and its argument:
String name = (String) table.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
ProcessBuilder p = new ProcessBuilder("cmd.exe", "cd", "/D", "%HOMEDRIVE%%HOMEPATH%/Desktop", "/c", "start", name);
According to: cmd.exe,
/D Ignore registry AutoRun commands
HKLM | HKCU \Software\Microsoft\Command Processor\AutoRun
Did you mean start.exe /D not cmd.exe /D?
and also they told that
If /C or /K is specified, then the remainder of the command line is processed as an immediate command in the new shell. Multiple commands separated by the command separator '&' or '&&' are accepted if surrounded by quotes.
Did you mean cmd.exe /C "cd %HOMEDRIVE%%HOMEPATH%\Desktop & Discord"?

Execute bash script and pass arguments with spaces from java

I know there are a lot of post about executing commands from Java but I just can't get this to work. Here is what I'm trying to do, I have a bash script, it receives 2 arguments which might or might not have spaces, then from Java I'm executing the script and passing the arguments like this(I'm surrounding the arguments with quotes and escaping them with backslashes):
String cmd = "/opt/myScript \"/opt/myPath1\" \"/opt/myPath2 with spaces\"";
Runtime rt = Runtime.getRuntime();
rt.exec(cmd);
I also tried to use the ProcessBuilder class like this:
String myScript = "/opt/myScript";
String myArg1= "/opt/myPath1";
String myArg2 = "/opt/myPath2 with spaces";
ProcessBuilder pb = new ProcessBuilder(myScript , myArg1, myArg2);
pb.start;
Arguments with no spaces are received successfully but I still have problems with the second one.
I thought the ProcessBuilder class would handle the spaces but seems like I'm missing something.
I'm not sure if it has something to do, but just in case here is my script:
#!/bin/bash
PATH=$PATH:$1
gnome-terminal --working-directory $2
$1 and $2 are the arguments sent from Java.
Get the same trouble, finally solved with:
Runtime.getRuntime().exec(new String[]{"bash", "-c", <command with spaces>});
Runtime.exec() is an overloaded method. There are several possible ways how to call it. The call exec(String command) executes the specified string command but the argument are separated by spaces here. The method exec(String[] cmdarray) executes the specified command and arguments. There are other exec() variants but the best for you is
String cmd[] = new String[] {"/opt/myScript", "/opt/myPath1", "/opt/myPath2 with spaces" };
Runtime rt = Runtime.getRuntime();
rt.exec(cmd);
It is possible to use ProcessBuilder can be used as well for argument passing. I think the only error is missing parenthesis after pb.start.
And last but not least the script has a major bug. It does not contain quutes arround $2. It should be
#!/bin/bash
PATH="$PATH:$1"
gnome-terminal --working-directory "$2"

Why does this java code get stuck?

I made a new process, but it never finishes.
I was trying with ProcessBuilder and Runtime but none of it worked, both got stuck.
Builder code:
ProcessBuilder a = new ProcessBuilder(
"java",
"-classpath",
"D:\\TAP",
"AnalizadorLexico",
"<",
"D:\\TAP\\Lol1.txt");
Process process=a.start();
Runtime code:
Process process=cmd.exec(
"java -classpath D:\\TAP AnalizadorLexico < D:\\TAP\\Lol1.txt ");
The command works in Windows CMD.
From comments:
The "<" works with cmd(or other shells). Java program does not interpret it as input. You can use "cmd /c java progr < input ", but that makes it windows specific.
A better way will be to use real Java APIs for it: See ProcessBuilder
Once you get past this , please check another FAQ item on this

Java execute debian terminal command with "|"

I am experiencing a really confusing issue about sending commands to terminal via Java.
I have exactly this code:
Process p = Runtime.getRuntime().exec(new String[]{"useradd", server, "-p", pass, "-d", "/home/dakadocp/servers/" + server, "-s", "/bin/false"});
Runtime.getRuntime().exec(new String[]{"echo", server + ":" + pass, "|", "chpasswd"});
The first command is this one "useradd user -p password -d /home/ftp/test/ -s /bin/false" and the second one should be this echo username:new_password | chpasswd, the first command works without any problem and creates the user which I define by the "server" variable, but when I try to execute the second command to change users pass this command probably never happen, output is null and the password is not changed, but when I type this command directly to the terminal it works perfectly so this is just Java issue.
I think the problem is in the character "|", before I tried also some command with "|" and its behavior was the same as with this command. What I am doing wrongly ?
Thanks.
Welite.
| is a shell feature, and requires a shell to run. The trivial fix is to run a shell:
Runtime.getRuntime().exec(new String[] { "sh", "-c", "echo something | chpasswd" });
However, java is more than capable of writing to a process with needing a shell or echo. The better way is to just run chpasswd by itself and writing the string to it:
Process p = Runtime.getRuntime().exec(new String[] { "chpasswd" });
PrintWriter writer = new PrintWriter(p.getOutputStream());
writer.println("foo:bar");
writer.close();

Passing a string to the Windows command line

Please see the code below
Runtime rt = Runtime.getRuntime();
rt.exec("cmd /c start");
String[] cmd = {"LogParser", "Select top 10 * into c:\temp\test9.csv from application" };
rt.exec(cmd);
It opens the command window but the strings are not passed in after opening. Can someone tell me why this code won't place the strings into the command window?
The option /C means: Carries out the command specified by the string and then terminates.
So the other command is handled as a separated one.
Use OutputStreamWriter and write to the input stream of the process created.
Process p = Runtime.getRuntime().exec("cmd /K start") ;
Writer w = new java.io.OutputStreamWriter(p.getOutputStream());
w.append(yourCommandHere);
Also, the reason for using /K :
/K Run Command and then return to the CMD prompt.
Reference : http://ss64.com/nt/cmd.html
Why not use this:
String[] cmd = { "cmd /c", "LogParser",
"Select top 10 * into c:\temp\test9.csv from application" };
rt.exec(cmd);
Find more info about the exec method here.
You'll first need to start a process as you do in your first two lines of code, but don't use start because that spawns a separate process and returns immediately. Use just LogParser instead, or whatever will make your LogParser process start without involving cmd. After that you need to retrieve the OutputStream of the Process object created by exec and write your select command into it. You will also need to read from the Processs InputStream to see the response. None of this will be visible in a separate command-prompt window; you'll need to process everything through Java and it will involve some multithreading as well.
As I said in my comment - 'They are executed as separate commands, they are not related just because you executed one before the other'
From the Runtime.exec( string ) javadoc -
Executes the specified command and arguments in a separate process.
You need to chain the commands together to get cmd to process your command, I believe you need to use the \k flag to specify what commands you need executed on the command line.
Runtime rt = Runtime.getRuntime();
String start = "cmd /k ";
String cmd = "LogParser;\n" Select top 10 * into c:\temp\test9.csv from application";
rt.exec(start + cmd);
Not tested as I don't have windows, but it should be similar to this.

Categories