【问题标题】:Execute commands in CMD on Windows with Java code在 Windows 上使用 Java 代码在 CMD 中执行命令
【发布时间】:2017-02-18 18:26:08
【问题描述】:

我想编写一个可以在 Windows CMD 中执行命令的 Java 代码。

我浏览了该网站并了解了如何发送和处理单个请求。例如创建新进程并在执行(“cmd /c dir”)然后使用输入流我可以得到显示的答案。

如何打开cmd进程让用户输入cmd命令?

例如,我打开应用程序,它直接打开 cmd 进程,然后用户可以输入“dir”并获取输出。

在键入“cd ../../”之后 然后再次输入“dir”并获得包含新路径的输出。

如果可以执行,那怎么办呢?或者为了执行这个需要每次打开一个新进程并执行("cmd /c some_reqests")?

【问题讨论】:

  • 只需使用控制台获取输入,然后使用用户输入启动执行进程。

标签: java windows cmd


【解决方案1】:

问得好,事实上你可以调用cmd作为一个新进程,使用标准输入和标准输出来处理数据。

棘手的部分是知道来自命令的流何时结束。

为此,我使用了在命令后回显的字符串 (dir && echo _end_)。

在实践中,我认为为每个任务简单地启动一个流程会更好。

public class RunCMD {

    public static void main(String[] args) {
        try {
            Process exec = Runtime.getRuntime().exec("cmd");
            OutputStream outputStream = exec.getOutputStream();
            InputStream inputStream = exec.getInputStream();
            PrintStream printStream = new PrintStream(outputStream);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
            printStream.println("chcp 65001");
            printStream.flush();
            printStream.println("dir && echo _end_");
            printStream.flush();


            for(String line=reader.readLine();line!=null;line=reader.readLine()){
                System.out.println(line);
                if(line.equals("_end_")){
                    break;
                }
            }

            printStream.println("exit");
            printStream.flush();

            for(String line=reader.readLine();line!=null;line=reader.readLine()){
                System.out.println(line);
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

【讨论】:

    【解决方案2】:

    试试这个

        Process p = Runtime.getRuntime().exec("ps -ef");
    

    在http://alvinalexander.com/java/edu/pj/pj010016找到它

    【讨论】:

    • 谢谢,希望对您有所帮助
    猜你喜欢
    • 2019-11-08
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多