Reputation: 63
I have to execute the following cmd
commands of Windows in Java.
The cmd
commands:
Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
//First i have to change my default directory//
C:\Users\shubh>D:
//Then move to a specific folder in the D drive.//
D:\>cd MapForceServer2017\bin\
//then execute the .mfx file from there.
D:\MapForceServer2017\bin>mapforceserver run C:\Users\shubh\Desktop\test1.mfx
Result of the execution
Output files:
library: C:\Users\shubh\Documents\Altova\MapForce2017\MapForceExamples\Tutorial\library.xml
Execution successful.
Upvotes: 1
Views: 12729
Reputation: 19
I had somewhat same requirement some time back and at that time I got the following snippet from stack I think. Try this.
String[] command =
{
"cmd",
};
Process p = Runtime.getRuntime().exec(command);
new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
stdin.println("dir c:\\ /A /Q");
// write any other commands you want here
stdin.close();
int returnCode = p.waitFor();
System.out.println("Return code = " + returnCode);
SyncPipe Class:
class SyncPipe implements Runnable
{
public SyncPipe(InputStream istrm, OutputStream ostrm) {
istrm_ = istrm;
ostrm_ = ostrm;
}
public void run() {
try
{
final byte[] buffer = new byte[1024];
for (int length = 0; (length = istrm_.read(buffer)) != -1; )
{
ostrm_.write(buffer, 0, length);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private final OutputStream ostrm_;
private final InputStream istrm_;
}
Upvotes: 0
Reputation: 31903
I suggest using https://commons.apache.org/proper/commons-exec/ for executing o/s command from within Java because it deals with various issues you may encounter later.
You can use:
CommandLine cmdLine = CommandLine.parse("cmd /c d: && cd MapForceServer2017\\bin\\ && mapforceserver run ...");
DefaultExecutor executor = new DefaultExecutor();
int exitValue = executor.execute(cmdLine);
Upvotes: 4