简体   繁体   English

无法在 Java 终端中运行多个命令

[英]Cannot run multiple commands in Java terminal

I cannot run multiple commands using symbols "&&", "&", "||", ";"我无法使用符号“&&”、“&”、“||”、“;”运行多个命令I checked almost every question that asked this, and I still could not find the answer to my problem.我检查了几乎所有提出这个问题的问题,但我仍然找不到问题的答案。 I can successfully run one command in the java command shell but not more than 1. Thank you in advance for your help!我可以成功运行 java 命令 shell 中的一个命令但不超过 1 个。提前感谢您的帮助!

try {

                Process process = Runtime.getRuntime().exec("g++ " + projPath +" -o " + name + " && ./" + name);
                StringBuilder output = new StringBuilder();

                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(process.getInputStream()));
                
                BufferedReader errinput = new BufferedReader(
                        new InputStreamReader(process.getErrorStream()));

                String line;
                String err;
                while ((line = reader.readLine()) != null) {
                    output.append(line + "\n");
                }
                while ((err = errinput.readLine()) != null) {
                    output.append(err + "\n");
                }

                int exitVal = process.waitFor();
                if (exitVal == 0) {
                    acc.setExpandedPane(pane1);
                    txt.setStyle("-fx-text-fill: black;");
                    txt.setText(output.toString());
                } else {
                    acc.setExpandedPane(pane1);
                    txt.setStyle("-fx-text-fill: red;");
                    txt.setText(output.toString());
                }

            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

Java does not provide a shell , it just splits the string provided into words and passes it as arguments to the executable mentioned as first word. Java 不提供shell ,它只是将提供的字符串拆分为单词并将其作为 arguments 传递给作为第一个单词提到的可执行文件。

Try passing the command to /bin/bash (or another shell of your choosing):尝试将命令传递给/bin/bash (或您选择的另一个 shell):

final String innerCommand = "g++ " + projPath +" -o " + name + " && ./" + name;
final String[] command = {"/bin/bash", "-c", innerCommand};
final Process process = Runtime.getRuntime().exec(command);

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

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