我想編譯Java程序下面的C代碼(語法錯誤已有意左):是否可以在Java中爲C程序打印出診斷信息?
/* Hello World program */
#include<stdio.h>
main()
{
printf("Hello World")
}
我希望我的java程序編譯C文件,並給在控制檯診斷。 示例:第4行;預計和行5無效的語法...
我已經安裝了CodeBlock MinGW編譯器,並已能夠獲得代碼編譯和打印出來的錯誤。
看一看我所做的:
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
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+="\n....\n";
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;
}
}
我得到以下結果:
....
hello.c: In function 'main':
hello.c:9:1: error: expected ';' before '}' token
但我想知道是否有可能從聽者得到診斷。我想要獲取行號,位置,語法錯誤的類型,這些錯誤將稍後輸入到數組中以供進一步處理。
下面是我想有像Java中:代替
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
List<CaptureErrors> myerrors = new ArrayList<CaptureErrors>();
MyDiagnosticListener listener = new MyDiagnosticListener();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(listener, null, null);
String fileToCompile = "C:\\Users\\User\\Desktop\\MyC.java";
Iterable fileObjects = fileManager.getJavaFileObjectsFromStrings(Arrays.asList(fileToCompile));
CompilationTask task = compiler.getTask(null, fileManager, listener, null, null, fileObjects);
Boolean result = task.call();
if(result == true){
System.out.println("Compilation has succeeded");
}
myerrors = listener.getlistofErrors();
for (CaptureErrors e : myerrors)
{
System.out.println("Code: " + e.getCode());
System.out.println("Kind: " + e.getKind());
System.out.println("Line Number: " + e.getLinenumber());
// System.out.println("Message: "+ e.getMessage(Locale.ENGLISH));
//System.out.println("Source: " + e.getSource());
System.out.println("End position: "+ e.getEndposition());
System.out.println("Position: "+ e.getPosition());
System.out.println("\n");
}
我想你必須自己解析來自C編譯器的響應來獲取行號和其他內容。 – 2013-02-12 13:29:21
請您詳細說明一下嗎? – user2026254 2013-02-12 13:30:16
我的意思是你有一個包含編譯器輸出的字符串'log'。該字符串包含有關編譯過程以及失敗原因的信息。你可以解析你的字符串,並手動獲取行號和其他內容。這很麻煩,但我不知道其他方式。 – 2013-02-12 13:32:59