2014-03-26 43 views
1

我想通過C#編譯一個Java程序。有誰知道爲什麼我不能接受程序的輸出,而我可以接受錯誤?我怎樣才能打印.java的結果?用C編譯java#

Process p = new Process(); p.StartInfo.FileName = "C:\\Program Files\\Java\\jdk1.7.0_04\\bin\\javac"; 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.Arguments = "c:\\java\\upgrade.java"; 
p.StartInfo.RedirectStandardInput = true; 
p.StartInfo.RedirectStandardError = true; 
p.StartInfo.CreateNoWindow = true; 
p.StartInfo.RedirectStandardOutput = true; 
p.Start(); 

p.WaitForExit();   

resultcode.Text = p.StandardOutput.ReadToEnd(); 
+1

你是什麼意思的「程序的輸出」?你的意思是編譯器的輸出嗎? –

回答

0

我想你的意思是「我如何從javac.exe捕獲stdout和stderr文本?」

你已經得到了大部分答案:

1)指定 「重定向」 在您的Process對象:

Process p = new Process(); 
p.StartInfo.FileName = @"C:\Program Files\Java\jdk1.7.0_04\bin\javac"; 
... 
p.StartInfo.RedirectStandardInput = true; 
p.StartInfo.RedirectStandardError = true; 

2)分配C#I/O對象重定向到:

StreamReader outputReader = null; 
StreamReader errorReader = null; 
... 
outputReader = p.StandardOutput; 
errorReader = p.StandardError; 

3)最後,從你的I/O對象閱讀:

string myText = "StdOut:" + Environment.NewLine; 
myText += outputReader.ReadToEnd(); 

myText += Environment.NewLine + "Stderr:" + Environment.NewLine; 
myText += errorReader.ReadToEnd(); 

Console.WriteLine("Complete output:" + myText); 

4)最後,如果你不要想要打開你自己的I/O對象,那麼不要設置p.StartInfo.RedirectStandardInput = true;