简体   繁体   English

Java命令提示符模拟器

[英]Java Command Prompt Emulator

I'm trying to make a java program that commands through cmd.exe and prints their output. 我正在尝试制作一个通过cmd.exe命令并输出其输出的Java程序。 To do this, I'm using this code: 为此,我使用以下代码:

cmdLine = Runtime.getRuntime().exec("cmd.exe");
cmdLineOut = new BufferedReader(new InputStreamReader(cmdLine.getInputStream()));
cmdLineIn = new PrintWriter(cmdLine.getOutputStream());
// ...
cmdLineIn.println(command);
cmdLineIn.flush();
String s = null;
while ((s = cmdLineOut.readLine()) != null)
    System.out.println(s);

Although, when input is given, the output is never printed. 虽然,当给出输入时,永远不会打印输出。

EDIT: Solved The cmdLineOut.readLine() doesn't return null when the input is empty, it freezes. 编辑:已解决当输入为空时,cmdLineOut.readLine()不会返回null,它会冻结。 Since readLine freezes at the end no other code is executed, I just put the printing of the readLine in a seperate thread. 由于readLine在最后冻结,因此没有其他代码执行,因此我只将readLine的打印放在单独的线程中。

If somebody wants to answer this better, go ahead. 如果有人想更好地回答这个问题,请继续。

You never actually execute the user's command, at least in the snippet you posted. 至少在发布的代码段中,您从未真正执行过用户的命令。 Also, nearly all command prompt "commands" are actually just programs that are on the default program search path. 另外,几乎所有命令提示符“命令”实际上只是默认程序搜索路径上的程序。 You should probably just Runtime.getRuntime().exec(user_command) for each command. 您应该只为每个命令运行Runtime.getRuntime().exec(user_command) This means that you will have to set up the input and output streams like you have already done for each command. 这意味着您将必须像对待每个命令一样设置输入和输出流。 You are right to get input in a separate thread, since attempting to read input will block the current thread until there is actually input to read. 您应该在单独的线程中获取输入,因为尝试读取输入将阻塞当前线程,直到实际有要读取的输入为止。 However, some commands, even under UNIX or Linux systems, are "built-in" (like cd ), meaning that the command prompt (aka "shell") handles the commands internally. 但是,即使在UNIX或Linux系统下,某些命令也是“内置的”(例如cd ),这意味着命令提示符(也称为“ shell”)在内部处理命令。 Your program will have to test the user input to see if they are calling a built-in, and specially handle calls to built-in commands. 您的程序必须测试用户输入以查看他们是否正在调用内置命令,并专门处理对内置命令的调用。 Your program should actually be portable to non-Windows computers. 您的程序实际上应该可移植到非Windows计算机。 Of course, the user would use different commands ( cp instead of copy ), but the only part you would have to add would be handling for other OS' shells' lists of built-ins (or simply have your program implement a "cross-platform" set of built-ins - this is your shell program, you get to make the rules). 当然,用户将使用不同的命令(用cp代替copy ),但是您唯一需要添加的部分就是处理其他OS外壳程序的内置列表(或者只是让您的程序实现“平台”内置函数集-这是您的Shell程序,您可以制定规则)。

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

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