gpt4 book ai didi

java - 通过java运行终端命令

转载 作者:太空宇宙 更新时间:2023-11-04 03:40:52 25 4
gpt4 key购买 nike

我必须从我的 java 程序在终端中执行两个命令。这是我正在使用的java代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Runterminal {

public static void main(String[] args) {

Process proc;
Process procRun;
String compileCommand = "aarch64-linux-g++ -std=c++14 hello.cpp";
String runCommand = "aarch64-linux-objdump -d a.out";
try{

proc = Runtime.getRuntime().exec(compileCommand);
procRun = Runtime.getRuntime().exec(runCommand);
// Read the output

BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));

String line = "";
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}

proc.waitFor();

BufferedReader readero =
new BufferedReader(new InputStreamReader(procRun.getInputStream()));

String lineo = "";
while((lineo = readero.readLine()) != null) {
System.out.print(lineo + "\n");
}

procRun.waitFor();
}
catch(Exception e)
{
System.out.println("Exception occurred "+e);
}

}
}

我的hello.cpp文件存储在主目录中。当我编译java程序时,它会被编译,但在运行时它会抛出异常。这是我得到的输出:

Exception occurred java.io.IOException: Cannot run program "aarch64-
linux-g++": error=2, No such file or directory

最佳答案

尝试在代码中使用以下行进行替换,

String compileCommand = "g++ -std=c++14 hello.cpp";
String runCommand = "./a.out";

并将 .cpp 文件保存在 .class 文件所在的同一目录中。

关于java - 通过java运行终端命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29690048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com