繁体   English   中英

在 Java 中,一个小帮助允许程序向 CMD.exe 发送命令

[英]In Java, a small help to allow a program send commands to CMD.exe

我正在尝试创建一个程序(个人练习)来访问 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.comnslookup google.com

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

这应该适合你:

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();
}

暂无
暂无

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

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