本文介绍了通过命令行从Java运行C / C ++程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个Java程序,该程序可以编译并执行C,c ++,java程序。.我首先对其进行了Java测试,并且运行良好。然后我对它进行了C语言测试,但出现了错误。请告诉我我该怎么做..这是编译代码的模块..:

I have written a java program that compiles and executes C,c++,java programs ..I firstly tested it for java and it worked absolutely fine. Then I tested it for C but it gave errors.Please tell what I need to do..Here is the module which compiles the code..:

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)


推荐答案

为使 g ++工作,Windows的PATH上必须有一个g ++。exe。如果它是 g ++。bat或 g ++。cmd,则必须使用确切名称调用Runtime.exec。

For "g++" to work, there has to be a g++.exe on the PATH for windows. If it is a "g++.bat" or "g++.cmd", you have to call Runtime.exec with the exact name.

这篇关于通过命令行从Java运行C / C ++程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 13:55
查看更多