简体   繁体   English

如何在 Java 中执行 Windows 命令?

[英]How do I execute Windows commands in Java?

I'm working on a project, and it will give you a list of Windows commands.我正在做一个项目,它会给你一个 Windows 命令列表。 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).我打算用 Visual C# 或 C++ 来做,但是 C++ 类太复杂了,我不想在 Visual C# 中制作表单和垃圾(在控制台应用程序中真的很糟糕)。

I hope this helps :)我希望这有帮助 :)

You could use:你可以使用:

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

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) {
}

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.我通常会构建一个通用类,您可以传入“命令”(例如“dir”)及其参数,该类会自动将调用附加到操作系统。 I would also included the ability to get the output, probably via a listener callback interface and even input, if the command allowed input...如果命令允许输入,我还将包括获取输出的能力,可能通过侦听器回调接口甚至输入...

This is a sample code to run and print the output of the ipconfig command 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/

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM