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.
Related
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"?
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"
I have a command like
cp -R Folder1/* Folder2/
or
rm -r /images/*.gif
It is not working to I try to run a sample program through Java
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
return proc.waitFor();
What am i doing wrong?
When you run a process, Java creates three outputs, the exit code, the STDOUT, and the STDERR. A good program running an external process, will check all three.
You are just waiting for the process to terminate, and return the exit code.
An easy way to see what's happening is to 'inherit' the STDOUT/STDERR streams using a ProcessBuilder:
ProcessBuilder pbuilder = new ProcessBuilder("cp", "-R", "Folder1/*", "Folder2/");
pbuilder.inheritIO();
Process proc = pbuilder.start();
return proc.waitFor();
you will get a better idea of what went wrong.
Note also that I used separate String arguments for the command. This helps with ensuring the arguments are passed right to the underlying process.
Try like this:
List<String> cmd = new ArrayList<String>();
cmd.add("bash");
cmd.add("-c");
cmd.add(" rm -rf *.txt");
add the above list in ProcessBuilder then execute.
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
I'm invoking the execution of a BAT file from Java with the Runtime object.
Is it possible to hide the BAT window during the execution of the script? How is it possible?
Try using javaw rather than java to run the script.
http://docs.oracle.com/javase/1.4.2/docs/tooldocs/windows/java.html
Update: Sorry, I think I read the question wrong. I know I've suppressed a .bat window doing something along these lines before:
http://www.geekstogo.com/forum/topic/56092-hide-the-command-prompt-windows/
Invoke start as the first command in your process builder, with the /b option:
ProcessBuilder builder = new ProcessBuilder("start", "/b", "<mybatchcommand>");
// .. set environment, handle streams
builder.start();
The /b options suppresses the command window.
Process p = Runtime.getRuntime().exec("scriptName.vbs");
In scriptName.vbs you write
var WindowStyle_Hidden = 0
var objShell = WScript.CreateObject("WScript.Shell")
var result = objShell.Run("cmd.exe /c abc.bat", WindowStyle_Hidden)