从Java通过命令行运行的AC / C ++程序(Running a c/c++ program f

2019-09-18 19:57发布

我写了编译和执行C,C ++,JAVA程序..我先测试了它的Java和它的工作精美绝伦的Java程序。 然后,我测试了它的C,但它给了errors.Please告诉我需要什么do..Here是编译代码的模块..:

public void compileCode(String path,String lang)throws IOException
    {
        String cmd="";
        if(lang.equals("c")||lang.equals("cpp"))
            cmd="g++ Main"+threadNum+"."+lang+" -o "+threadNum;
        else if(lang.equals("java"))
            cmd="javac Main"+threadNum+".java";

        Process p=Runtime.getRuntime().exec(cmd,null,new File(path));

         String s=null;
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        while ((s = stdError.readLine()) != null) {
            msg+=s+"\n";
            res=0;
        }
        if(res!=0)
            processCode(path,lang);
    }

而错误的是:

Exception in thread "main" java.io.IOException: Cannot run program "g++" (in directory "C:\wamp\www\usercodes\lokesh"): CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    at java.lang.Runtime.exec(Runtime.java:615)
    at java.lang.Runtime.exec(Runtime.java:448)
    at Contest.compileCode(Main.java:164)
    at Contest.makeFile(Main.java:154)
    at Contest.main(Main.java:52)
    at Main.main(Main.java:14)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:1

20)

Answer 1:

对于“G ++”的工作,必须有对PATH为Windows G ++。exe文件。 如果它是一个“G ++。蝙蝠”或“G ++。CMD”,你要调用的Runtime.exec与确切名称。



Answer 2:

我使用的过程,而不是生成器,它的工作out..Anyways日Thnx乌拉圭回合时间:)下面的代码...

public void compileCode(String path,String lang)throws IOException,InterruptedException
    {
        String cmd="";
        if(lang.equals("c")||lang.equals("cpp"))
            cmd="g++ "+path+"Main"+threadNum+"."+lang+" -o "+threadNum;
        else if(lang.equals("java"))
            cmd="javac Main"+threadNum+".java";
        ProcessBuilder process=new ProcessBuilder();
        process.directory(new File(path));
        process.command(new String[]{"cmd","/c",cmd});
        Process p=process.start();
        String s=null;
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        while ((s = stdError.readLine()) != null) {
            msg+=s+"\n";
            res=0;
        }
        if(res!=0)
            processCode(path,lang);
    }


文章来源: Running a c/c++ program from java through command line