70

我发现了几个通过 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

如何使用 Java 打开命令提示符并插入命令?

任何人都可以帮助我了解如何 cd 一个目录,例如:

 cd C:\Program Files\Flowella

然后在该目录上运行其他命令?

4

14 回答 14

149

将进程从不同目录运行到 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);
        }
    }
}

另请注意,我正在使用 aProcessBuilder来运行命令。除其他外,这允许我通过调用将进程的标准错误重定向到其标准输出中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
于 2013-03-17T18:23:25.843 回答
14

你可以试试这个: -

Process p = Runtime.getRuntime().exec(command);
于 2013-03-17T17:53:39.057 回答
8

如果您想执行类似的操作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();

将命令和所有参数拆分为字符串数组的单独字符串很重要(否则ProcessBuilderAPI 将无法正确提供它们)。

于 2014-12-13T22:59:02.430 回答
6

这是一个更完整的命令行执行实现。

用法

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);
}
于 2017-12-27T16:19:09.390 回答
4

我的例子(来自真实项目)

文件夹——文件。

zipFile,filesString — 字符串;

        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);
            }
        }
于 2013-03-17T18:08:32.090 回答
4

尝试这个:

Process runtime = Runtime.getRuntime().exec("cmd /c start notepad++.exe");
于 2016-07-03T22:32:08.997 回答
3

最简单的方法是使用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();
}

如有必要,然后使用 aScanner获取命令的输出。

Scanner kb = new Scanner(process.getInputStream());

注意: the\是 a 中的转义字符String,必须转义才能正常工作(因此是\\)。


但是,没有名为 的可执行文件cd,因为它不能在单独的进程中实现。

当前工作目录很重要的一种情况是执行外部进程(使用ProcessBuilderor Runtime.exec())。在这些情况下,您可以明确指定用于新启动进程的工作目录。

最简单的命令方式:

System.setProperty("user.dir", "C:\\Program Files\\Flowella");
于 2013-03-17T17:53:03.957 回答
2

一旦获得对 Process 的引用,就可以对其调用 getOutpuStream 以获取 cmd 提示符的标准输入。然后,您可以使用 write 方法在流上发送任何命令,就像使用任何其他流一样。

请注意,它是 process.getOutputStream() 连接到衍生进程上的标准输入。类似地,要获取任何命令的输出,您需要调用 getInputStream,然后将其作为任何其他输入流读取。

于 2013-03-17T18:02:36.907 回答
2

公共类演示{公共静态无效主(字符串参数[])抛出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);
    }
}

}
于 2020-01-11T16:50:14.420 回答
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();
}
于 2020-12-29T14:43:05.020 回答
1

你不能这样运行cd,因为cd它不是一个真正的程序;它是命令行的内置部分,它所做的只是改变命令行的环境。在子进程中运行它是没有意义的,因为那时您正在更改该子进程的环境 - 但该子进程立即关闭,丢弃其环境。

要在您的实际 Java 程序中设置当前工作目录,您应该编写:

System.setProperty("user.dir", "C:\\Program Files\\Flowella");
于 2013-03-17T18:12:35.763 回答
1

从 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();
    }
}
于 2019-03-18T02:42:32.613 回答
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);


}

}

于 2020-01-04T21:21:41.580 回答
0

最简单和最短的方法是使用CmdTool库。

new Cmd()
         .configuring(new WorkDir("C:/Program Files/Flowella"))
         .command("cmd.exe", "/c", "start")
         .execute();

您可以在此处找到更多示例。

于 2018-04-24T10:49:35.280 回答