通过java运行终端命令

时间:2015-04-17 04:03:08

标签: java linux terminal command

我必须从我的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

1 个答案:

答案 0 :(得分:0)

尝试使用代码中的以下行替换

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

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