[英]How to open Command Prompt, change directory and execute a command using Java code (Windows)
The title basically says it all. 标题基本上说明了一切。 What I've been able to do so far, by searching around on the web, is the following:
到目前为止,通过在网上搜索,我已经能够做到以下几点:
Runtime rt = Runtime.getRuntime();
try {
Process proc = rt.exec("cmd /c start cmd.exe /K \"cd " + locaction);
}
catch (Exception e) {
//...
}
where location
is the String representation of the directory I'd like to switch to. 其中
location
是我要切换到的目录的字符串表示形式。 Not sure if the above is the best way to do that, but either way, how do I then run a certain command from that directory (say, eg, there's an application there and I want it to run)? 不知道上面是否是执行此操作的最佳方法,但是无论哪种方法,我该如何从该目录运行某个命令(例如,那里有一个应用程序,我希望它运行)? Thanks.
谢谢。
If you just want to run an application with a specific working directory, the easiest way is to use a ProcessBuilder
: 如果您只想运行具有特定工作目录的应用程序,则最简单的方法是使用
ProcessBuilder
:
ProcessBuilder pb = new ProcessBuilder(executable, arguments, if, any);
pb.directory(theWorkingDirectory);
pb.start();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.