如何在Java中更改目录并执行文件
我必须在Java中执行以下Windows的cmd
命令。如何在Java中更改目录并执行文件
的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
执行
Output files:
library: C:\Users\shubh\Documents\Altova\MapForce2017\MapForceExamples\Tutorial\library.xml
Execution successful.
我建议使用https://commons.apache.org/proper/commons-exec/用于Java内部从执行O/S命令,因为它有各种问题的交易结果你稍后可能会遇到。
您可以使用:
CommandLine cmdLine = CommandLine.parse("cmd /c d: && cd MapForceServer2017\\bin\\ && mapforceserver run ...");
DefaultExecutor executor = new DefaultExecutor();
int exitValue = executor.execute(cmdLine);
+1使用'&&'并使用第三方库来处理子流程。顺便提一下,您可以用'cd/d D:\\ MapForceServer ...'替换'd:&& cd MapForceServer ...':'/ d'开关允许您同时更改驱动器和目录。 –
感谢cherouivm对你的回答以及Luke Woodward的评论。基本上我所做的就是使用两种创建批处理文件(由harshavmb建议的方法)的方法的组合,它具有多个命令并且使用cherouvim的方法使用commandline.parse()函数用字符串变量调用该批处理文件,该变量将变量的值(基本上是用户上传的文件名)发送到批处理文件以供进一步执行。 – shubham0001
@ shubham0001创建一个批处理文件看起来像是一种矫枉过正的情况,以防万一你需要执行的命令总数不是那么多。你可以用'&&'连接它们。 – cherouvim
我有些同样的要求,一段时间回来,当时我从堆下面的代码片段,我认为。尝试这个。
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 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_;
}
你为什么不尝试在Windows的.bat脚本?只是一个想法! – harshavmb
我希望在我的servlet文件中添加上述命令的java代码,用户将上传文件,然后它将被mapforceserver run命令使用。因此,每次用户上传新文件时,文件名都会更改。我们可以在运行期间动态更改批处理文件的内容吗? – shubham0001
是的,你可以使用java.io.File API编写,通过下面的链接。 http://stackoverflow.com/questions/29820079/write-into-bat-file-with-java – harshavmb