-2

如果我正在用 java 编写自己的编辑器,那么是否可以运行用 C 编程语言编写的程序?如果是,那么如何?

4

2 回答 2

0

您可以使用 exec 系列来运行进程。这是你用来执行此操作的片段,并读取该过程的输出,以便我知道它做了什么。您可能希望在 IDE 中使用它来解析来自 gcc 的错误消息。

        Process proc = Runtime.getRuntime().exec("mycommand");
        BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line;
        while ((line = input.readLine()) != null)
        {
            // Here you can parse the output of the process.
            System.out.println(line);
        }
于 2013-09-13T07:53:45.350 回答
0

尝试这个:

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

public class C_Compile {
public static void main(String args[]){

    String ret = compile();
    System.out.println(ret);

}
    public static String compile()
    {
        String log="";
        String myDirectory = "C:\\";
         try {
             String s= null;
           //change this string to your compilers location,Assume C file is in c:\\Hello.c
             Process p = Runtime.getRuntime().exec("cmd /C gcc Hello.c", null, new java.io.File(myDirectory));

         BufferedReader stdError = new BufferedReader(new 
              InputStreamReader(p.getErrorStream()));
         boolean error=false;

         log+="";
         while ((s = stdError.readLine()) != null) {
             log+=s;
             error=true;
             log+="\n";

         }
         if(error==false) log+="Compilation Successful !!!";

     } catch (IOException e) {
         e.printStackTrace();
     }
         return log;
    }


  public int runProgram() 
    {
        int ret = -1;
       try
         {            
             Runtime rt = Runtime.getRuntime();
             Process proc = rt.exec("cmd.exe /c start a.exe");
             proc.waitFor();
             ret = proc.exitValue();
         } catch (Throwable t)
           {
             t.printStackTrace();
             return ret;
           }
       return ret;                      
    }}
于 2013-09-13T07:53:15.657 回答