如何在 Java 中执行 Windows 命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16452964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:59:43  来源:igfitidea点击:

How do I execute Windows commands in Java?

javawindowscmd

提问by user2364493

I'm working on a project, and it will give you a list of Windows commands. When you select one, it will perform that command. However, I don't know how to do that. I was going to do it in Visual C#, or C++, but C++ classes are too complicated, and I don't want to make the forms and junk in Visual C# (really bad at console applications).

我正在做一个项目,它会给你一个 Windows 命令列表。当您选择一个时,它将执行该命令。但是,我不知道该怎么做。我打算用 Visual C# 或 C++ 来做,但是 C++ 类太复杂了,我不想在 Visual C# 中制作表单和垃圾(在控制台应用程序中真的很糟糕)。

回答by Bevilacqua

I hope this helps :)

我希望这有帮助 :)

You could use:

你可以使用:

Runtime.getRuntime().exec("ENTER COMMAND HERE");

回答by Bevilacqua

an example. 1. create cmd 2. write to cmd -> call a command.

一个例子。1. 创建 cmd 2. 写入 cmd -> 调用命令。

try {
    // Execute command
    String command = "cmd /c start cmd.exe";
    Process child = Runtime.getRuntime().exec(command);

    // Get output stream to write from it
    OutputStream out = child.getOutputStream();

    out.write("cd C:/ /r/n".getBytes());
    out.flush();
    out.write("dir /r/n".getBytes());
    out.close();
} catch (IOException e) {
}

回答by MadProgrammer

Take advantage of the ProcessBuilder.

充分利用ProcessBuilder.

It makes it easier to build the process parameters and takes care of issues with having spaces in commands automatically...

它可以更轻松地构建过程参数并自动处理命令中的空格问题...

public class TestProcessBuilder {

    public static void main(String[] args) {

        try {
            ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "dir");
            pb.redirectError();
            Process p = pb.start();
            InputStreamConsumer isc = new InputStreamConsumer(p.getInputStream());
            isc.start();
            int exitCode = p.waitFor();

            isc.join();
            System.out.println("Process terminated with " + exitCode);
        } catch (IOException | InterruptedException exp) {
            exp.printStackTrace();
        }

    }

    public static class InputStreamConsumer extends Thread {

        private InputStream is;

        public InputStreamConsumer(InputStream is) {
            this.is = is;
        }

        @Override
        public void run() {

            try {
                int value = -1;
                while ((value = is.read()) != -1) {
                    System.out.print((char)value);
                }
            } catch (IOException exp) {
                exp.printStackTrace();
            }

        }

    }
}

I'd generally build a all purpose class, which you could pass in the "command" (such as "dir") and it's parameters, that would append the call out to the OS automatically. I would also included the ability to get the output, probably via a listener callback interface and even input, if the command allowed input...

我通常会构建一个通用类,您可以传入“命令”(例如“dir”)及其参数,该类会自动将调用附加到操作系统。如果命令允许输入,我还将包括获取输出的能力,可能通过侦听器回调接口甚至输入...

回答by Swastik Padhi

Old question but might help someone passing by. This is a simple and working solution. Some of the above solutions don't work.

老问题,但可能会帮助路过的人。这是一个简单而有效的解决方案。上述一些解决方案不起作用。

import java.io.IOException;
import java.io.InputStream;

public class ExecuteDOSCommand
{
    public static void main(String[] args)
    {
        final String dosCommand = "cmd /c dir /s";
        final String location = "C:\WINDOWS\system32";
        try
        {
            final Process process = Runtime.getRuntime().exec(dosCommand + " " + location);
            final InputStream in = process.getInputStream();
            int ch;
            while((ch = in.read()) != -1)
            {
                System.out.print((char)ch);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

Source: http://www.devx.com/tips/Tip/42644

来源:http: //www.devx.com/tips/Tip/42644

回答by Akshay Pethani

This is a sample code to run and print the output of the ipconfigcommand in the console window.

这是一个示例代码,用于在控制台窗口中运行和打印ipconfig命令的输出。

import java.io.IOException;
import java.io.InputStream;

public class ExecuteDOSCommand {
    public static void main(String[] args) {
        final String dosCommand = "ipconfig";
        try {
            final Process process = Runtime.getRuntime().exec(dosCommand );
            final InputStream in = process.getInputStream();
            int ch;
            while((ch = in.read()) != -1) {
                System.out.print((char)ch);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Source: https://www.codepuran.com/java/execute-dos-command-java/

来源:https: //www.codepuran.com/java/execute-dos-command-java/