简体   繁体   English

如何使用Java代码打开命令提示符,更改目录和执行命令(Windows)

[英]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.

相关问题 使用命令提示符执行.java - Using command prompt to execute .java 如何在 OSX 中使用 java 代码打开终端并执行命令 - How to open Terminal and execute command using java code in OSX 如何通过Java执行命令提示符命令 - How to execute command prompt command through java 如何使用Java更改命令提示符中的路径 - How to change the path in command prompt using java 我能够从Java程序中打开命令提示符,如何使用Java代码在此命令提示符中运行某些exe? - I was able to open a command prompt from my Java program, How to run some exe in this command prompt using java code? 如何在Windows中使用Java中的processBuilder来执行带有参数的exe命令 - How to use processBuilder in Java to execute an exe with arguments in Windows Command Prompt 如何在Windows命令提示符下使用单个命令获取java版本? - How to get java version using single command in Windows command prompt? 如何在java中更改user.dir(或命令提示符中的当前目录)? - How to change user.dir ( or current directory in command prompt ) in java? 如何在Windows上使用Java执行Linux命令? - how execute linux command using java on windows? 如何使用带有Java编程的Eclipse打开Windows命令提示符? - How do you open the Windows Command prompt using eclipse with java programming?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM