我找到了几个用于通过Java类运行cmd命令的代码片段,但我无法理解它。
这是打开cmd的代码
public void excCommand(String new_dir){
Runtime rt = Runtime.getRuntime();
try {
rt.exec(new String[]{"cmd.exe","/c","start"});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我找到了一些其他链接来添加其他命令,比如cd http://www.coderanch.com/t/109753/Linux-UNIX/exec-command-cd-command-java
How to open the command prompt and insert commands using Java?
任何人都可以帮助我理解如何cd目录,如:
cd C:\Program Files\Flowella
然后在该目录上运行其他命令?
答案 0 :(得分:118)
将进程从不同目录运行到Java程序的工作目录的一种方法是更改目录,然后在同一命令行中运行该进程。您可以通过cmd.exe
运行命令行来执行此操作,例如cd some_directory && some_program
。
以下示例更改为其他目录并从那里运行dir
。不可否认,我只需要dir
该目录,而无需cd
,但这只是一个例子:
import java.io.*;
public class CmdTest {
public static void main(String[] args) throws Exception {
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "cd \"C:\\Program Files\\Microsoft SQL Server\" && dir");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) { break; }
System.out.println(line);
}
}
}
另请注意,我正在使用ProcessBuilder
来运行命令。除此之外,这允许我通过调用redirectErrorStream(true)
将进程的标准错误重定向到其标准输出。这样做只给我一个流来读取。
这在我的机器上给出了以下输出:
C:\Users\Luke\StackOverflow>java CmdTest
Volume in drive C is Windows7
Volume Serial Number is D8F0-C934
Directory of C:\Program Files\Microsoft SQL Server
29/07/2011 11:03 <DIR> .
29/07/2011 11:03 <DIR> ..
21/01/2011 20:37 <DIR> 100
21/01/2011 20:35 <DIR> 80
21/01/2011 20:35 <DIR> 90
21/01/2011 20:39 <DIR> MSSQL10_50.SQLEXPRESS
0 File(s) 0 bytes
6 Dir(s) 209,496,424,448 bytes free
答案 1 :(得分:9)
你可以试试这个: -
Process p = Runtime.getRuntime().exec(command);
答案 2 :(得分:5)
如果您想执行cd
等操作,请使用:
String[] command = {command_to_be_executed, arg1, arg2};
ProcessBuilder builder = new ProcessBuilder(command);
builder = builder.directory(new File("directory_location"));
示例:
String[] command = {"ls", "-al"};
ProcessBuilder builder = new ProcessBuilder(command);
builder = builder.directory(new File("/ngs/app/abc"));
Process p = builder.start();
将命令和所有参数拆分为字符串数组的单独字符串非常重要(否则ProcessBuilder
API无法正确提供它们。)
答案 3 :(得分:3)
我的例子(来自真实的项目)
文件夹 - 文件。
zipFile,filesString - String;
final String command = "/bin/tar -xvf " + zipFile + " " + filesString;
logger.info("Start unzipping: {} into the folder {}", command, folder.getPath());
final Runtime r = Runtime.getRuntime();
final Process p = r.exec(command, null, folder);
final int returnCode = p.waitFor();
if (logger.isWarnEnabled()) {
final BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = is.readLine()) != null) {
logger.warn(line);
}
final BufferedReader is2 = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = is2.readLine()) != null) {
logger.warn(line);
}
}
答案 4 :(得分:2)
最简单的方法是使用Runtime.getRuntime.exec()
。
例如,要在Windows上获取默认浏览器的注册表值:
String command = "REG QUERY HKEY_CLASSES_ROOT\\http\\shell\\open\\command";
try
{
Process process = Runtime.getRuntime().exec(command);
} catch (IOException e)
{
e.printStackTrace();
}
然后使用Scanner
获取命令的输出(如有必要)。
Scanner kb = new Scanner(process.getInputStream());
注意:\
是String
中的转义字符,必须转义才能正常工作(因此\\
)。
但是,没有名为cd
的可执行文件,因为它无法在单独的进程中实现。
当前工作目录很重要的一种情况是执行外部流程(使用ProcessBuilder
或Runtime.exec()
)。在这些情况下,您可以明确指定用于新启动的进程的工作目录。
最简单的命令方式:
System.setProperty("user.dir", "C:\\Program Files\\Flowella");
答案 5 :(得分:2)
试试这个:
Process runtime = Runtime.getRuntime().exec("cmd /c start notepad++.exe");
答案 6 :(得分:2)
这是一个更完整的命令行执行实现。
executeCommand("ls");
<强>输出:强>
12/27/2017 11:18:11:732: ls
12/27/2017 11:18:11:820: build.gradle
12/27/2017 11:18:11:820: gradle
12/27/2017 11:18:11:820: gradlew
12/27/2017 11:18:11:820: gradlew.bat
12/27/2017 11:18:11:820: out
12/27/2017 11:18:11:820: settings.gradle
12/27/2017 11:18:11:820: src
private void executeCommand(String command) {
try {
log(command);
Process process = Runtime.getRuntime().exec(command);
logOutput(process.getInputStream(), "");
logOutput(process.getErrorStream(), "Error: ");
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private void logOutput(InputStream inputStream, String prefix) {
new Thread(() -> {
Scanner scanner = new Scanner(inputStream, "UTF-8");
while (scanner.hasNextLine()) {
synchronized (this) {
log(prefix + scanner.nextLine());
}
}
scanner.close();
}).start();
}
private static SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss:SSS");
private synchronized void log(String message) {
System.out.println(format.format(new Date()) + ": " + message);
}
答案 7 :(得分:2)
可以通过以下代码停止和禁用服务:
static void sdService() {
String[] cmd = {"cmd.exe", "/c", "net", "stop", "MSSQLSERVER"};
try {
Process process = new ProcessBuilder(cmd).start();
process.waitFor();
String line = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
line = null;
bufferedReader = null;
Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= disabled");
p.waitFor();
bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
可以通过以下代码启用和启动服务
static void esService() {
String[] cmd = {"cmd.exe", "/c", "net", "start", "MSSQLSERVER"};
try {
Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= auto");
//Process p = Runtime.getRuntime().exec("sc config MSSQLSERVER start= demand");
p.waitFor();
String line = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
line = null;
bufferedReader = null;
Process process = new ProcessBuilder(cmd).start();
process.waitFor();
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
可以通过以下代码从任何文件夹执行命令。
static void runFromSpecificFolder() {
try {
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "cd \"C:\\Users\\himan\\Desktop\\Java_Test_Deployment\\jarfiles\" && dir");
//processBuilder.directory(new File("C://Users//himan//Desktop//Java_Test_Deployment//jarfiles"));
processBuilder.redirectErrorStream(true);
Process p = processBuilder.start();
p.waitFor();
String line = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
sdService();
runFromSpecificFolder();
esService();
}
答案 8 :(得分:1)
获得对Process的引用后,可以在其上调用getOutpuStream来获取cmd提示符的标准输入。然后,您可以使用write方法通过流发送任何命令,就像使用任何其他流一样。
请注意,它是process.getOutputStream(),它连接到生成进程上的stdin。同样,要获取任何命令的输出,您需要调用getInputStream,然后将其作为任何其他输入流读取。
答案 9 :(得分:1)
您不能以这种方式运行cd
,因为cd
不是真正的程序;它是命令行的内置部分,它所做的就是改变命令行的环境。在子进程中运行它是没有意义的,因为那时你正在改变那个子进程的环境 - 但是这个子进程会立即关闭,丢弃它的环境。
要在实际的Java程序中设置当前工作目录,您应该写:
System.setProperty("user.dir", "C:\\Program Files\\Flowella");
答案 10 :(得分:1)
公共课程演示{ 公共静态void main(String args [])引发IOException {
Process process = Runtime.getRuntime().exec("/Users/******/Library/Android/sdk/platform-tools/adb" + " shell dumpsys battery ");
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while (true) {
line = in.readLine();
if (line == null) { break; }
System.out.println(line);
}
}
}
答案 11 :(得分:0)
最简单和最简短的方法是使用CmdTool库。
new Cmd()
.configuring(new WorkDir("C:/Program Files/Flowella"))
.command("cmd.exe", "/c", "start")
.execute();
您可以找到更多示例here。
答案 12 :(得分:0)
从Java执行cmd的方法之一!
public void executeCmd() {
String anyCommand="your command";
try {
Process process = Runtime.getRuntime().exec("cmd /c start cmd.exe /K " + anyCommand);
} catch (IOException e) {
e.printStackTrace();
}
}
答案 13 :(得分:0)
这里的增值器是使用&符号来批处理命令并使用cd更改驱动器的正确格式。
public class CmdCommander {
public static void main(String[] args) throws Exception {
//easyway to start native windows command prompt from Intellij
/*
Rules are:
1.baseStart must be dual start
2.first command must not have &.
3.subsequent commands must be prepended with &
4.drive change needs extra &
5.use quotes at start and end of command batch
*/
String startQuote = "\"";
String endQuote = "\"";
//String baseStart_not_taking_commands = " cmd /K start ";
String baseStart = " cmd /K start cmd /K ";//dual start is must
String first_command_chcp = " chcp 1251 ";
String dirList = " &dir ";//& in front of commands after first command means enter
//change drive....to yours
String changeDir = " &cd &I: ";//extra & makes changing drive happen
String javaLaunch = " &java ";//just another command
String javaClass = " Encodes ";//parameter for java needs no &
String javaCommand = javaLaunch + javaClass;
//build batch command
String totalCommand =
baseStart +
startQuote +
first_command_chcp +
//javaCommand +
changeDir +
dirList +
endQuote;
System.out.println(totalCommand);//prints into Intellij terminal
runCmd(totalCommand);
//Thread t = Thread.currentThread();
//t.sleep(3000);
System.out.println("loppu hep");//prints into Intellij terminal
}
public static void runCmd(String command) throws Exception {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command);
}
}