简体   繁体   中英

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

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.

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 Process s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM