[英]How to change directory and execute a file there in Java
I have to execute the following cmd
commands of Windows in Java. 我必须在Java中执行Windows的以下
cmd
命令。
The cmd
commands: cmd
命令:
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.
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. 我建议使用https://commons.apache.org/proper/commons-exec/从Java内部执行o / s命令,因为它处理了以后可能遇到的各种问题。
You can use: 您可以使用:
CommandLine cmdLine = CommandLine.parse("cmd /c d: && cd MapForceServer2017\\bin\\ && mapforceserver run ...");
DefaultExecutor executor = new DefaultExecutor();
int exitValue = executor.execute(cmdLine);
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: SyncPipe类别:
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_;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.