Running terminal commands throug java

余生长醉 提交于 2019-12-12 05:06:35

问题


I have to execute two commands in terminal from my java program. Here is the java code that I am using :

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

  }
} 

My hello.cpp file is stored in the home directory. When I compile the java program it gets compiled but while running it it is throwing exception. Here's the output which I am getting :

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

回答1:


Try to replace using following lines in your code,

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

And keep the .cpp file in same directory where the .class file lies.



来源:https://stackoverflow.com/questions/29690048/running-terminal-commands-throug-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!