有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

cmd如何在不单独启动的情况下作为java程序的一部分使用?

我想创建一个java程序,它可以从用户那里获取输入,并将该输入传递给cmd,然后获取并向用户显示输出。我在互联网上看到过很多例子,但它们只告诉我们如何从外部开始。但我不想开始。我想使用cmd作为程序的一部分,这样它就不会打开,而只会像对输入执行一些不可见的操作并返回输出一样工作。有人知道吗

我也尝试过在这个网站上搜索类似的问题,但没有找到。抱歉,如果是重复的


共 (1) 个答案

  1. # 1 楼答案

    你可以用Runtime#exec来做这个。 下面的代码片段显示了如何读取在cmd中执行的特定命令的输出。exe

    public static String executeCommand(String command) throws IOException
    {
        StringBuilder outputBuilder = new StringBuilder();
        Process process = Runtime.getRuntime().exec(new String[] {"cmd", "/c", command});
        BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String read = null;
        while((read = outputReader.readLine()) != null)
        {
            outputBuilder.append(read).append("\n");
        }
        outputReader.close();
        process.destroy();
        return outputBuilder.toString();
    }
    

    下面的示例显示了如何与流程交互

    public static void main(String[] args) throws Exception {
        Process process = Runtime.getRuntime().exec(new String[]{"cmd", "/c", "cmd" /* Replace with the name of the executable */});
        Scanner scanner = new Scanner(System.in);
        PrintWriter printWriter = new PrintWriter(process.getOutputStream());
        BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        new Thread(() -> {
            try {
                String read = null;
                while ((read = outputReader.readLine()) != null) {
                    System.out.println("Process -> " + read);
                }
                System.out.println("Finished executing.");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        while (scanner.hasNext()) {
            String cmd = scanner.nextLine();
            System.out.println(cmd + " -> Process");
            printWriter.write(cmd + "\n");
            printWriter.flush();
        }
        scanner.close();
        printWriter.close();
        outputReader.close();
        process.destroy();
    }