【问题标题】:In Java, a small help to allow a program send commands to CMD.exe在 Java 中,允许程序向 CMD.exe 发送命令的小帮助
【发布时间】:2020-09-29 01:25:40
【问题描述】:

我正在尝试创建一个程序(个人练习)来访问 CMD 并键入您想要的任何命令,就好像您正在使用 cmd.exe 一样;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class CMD_Live {

    public static void main(String[] args) throws IOException {

        // The purpose of this program is to use Java to perform CMD commands as if you are working on it live

        Scanner ScanCMD = new Scanner(System.in); 

        while(true) {

            System.out.print("Insert your Command> ");
            String CMDcommand = ScanCMD.nextLine();

            Process processToCMD = Runtime.getRuntime().exec(CMDcommand);
            BufferedReader readerToCMD = new BufferedReader(new InputStreamReader(processToCMD.getInputStream()));

            String line;
            while ((line = readerToCMD.readLine()) != null) {
                System.out.println(line);
            }

            System.out.println();
            readerToCMD.close();
        }

    }

}

这段代码的问题是,它适用于简单的命令, 例如 ping google.com,或 nslookup google.com

但如果我插入 nslookup 并按 Enter 进入高级模式,那么响应就会消失。 有办法解决吗?

【问题讨论】:

  • 最后再次使用 System.in.readLine 吗?

标签: java cmd command-line operating-system command


【解决方案1】:

这应该适合你:

ProcessBuilder processBuilder = new ProcessBuilder(CMDcommand); //note, that you can build your command here step by step.
Process process = processBuilder.start();
String response = null;

InputStream inputStream = process.getInputStream();
BufferedReader bufferedInputStream = new BufferedReader(new InputStreamReader(inputStream));

//and then do whatever you want to do.. my example is this:
while(response=bufferedInputStream.readLine()!=null) {
    ..some code..
}
} catch (IOException e) {
    e.printStackTrace();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    • 2010-11-14
    相关资源
    最近更新 更多