2012-03-23 44 views
2

我想使用C#進程從命令提示符中獲取結果。該命令是 「的Java的HelloWorld 1」(我已經建立它使用「的javac HelloWorld.java」 HelloWorld.class的文件)​​C#調用java.exe並從cmd中獲取結果錯誤

Java代碼:

public class HelloWorld { 

    public HelloWorld() {} 

    public static void main(String[] args) { System.out.println("STARTED"); 
     try { 
      int param = Integer.parseInt(args[0].toString()); 
      if (param == 1) { 
       System.out.println("BASE 64!"); 
      } else if (param == 2) { 
       System.out.println("MD5!"); 
      } else { 
       System.out.println("INPUT NOT MATCH!"); 
      } 
     } catch (Exception ee) { 
      System.out.println("NO INPUT - ERROR"); 
     } 
    } } 

和C#代碼:

System.Diagnostics.Process p = new System.Diagnostics.Process(); 
    p.StartInfo.FileName = "C:\\Program Files\\Java\\jdk1.6.0_25\\bin\\java.exe"; 
    p.StartInfo.Arguments = "HelloWorld 1"; 
    p.StartInfo.UseShellExecute = false; 
    p.StartInfo.RedirectStandardOutput = true; 
    p.Start(); 
    string strOutput = p.StandardOutput.ReadToEnd(); 
    p.WaitForExit(); 

但strOutput是「」。 你能給我解決方案嗎? 謝謝!

回答

3

最有可能的是,java無法找到您的HelloWorld.class文件。

在這種情況下,它會寫入標準錯誤像

Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld 
Caused by: java.lang.ClassNotFoundException: HelloWorld 

,然後堆棧跟蹤。

,也不會寫東西到標準輸出

我建議你做兩件事情:

1)從標準錯誤,以及看看,說什麼

2)添加類路徑參數之前的類文件

p.StartInfo.Arguments = " -cp C:\\code\\myapp HelloWorld 1"; 

(在正確的路徑包含的HelloWorld.class的文件夾顯然代)

+0

我使用cmd「javac HelloWorld.java」來構建HelloWorld.class,並將代碼更改爲:p.StartInfo.FileName = 「C:\\ Program Files \\ Java \\ jdk1.6.0_25 \\ bin \\ java.exe」; p.StartInfo.Arguments =「-cp C:\\ Program Files \\ Java \\ jdk1.6.0_25 \\ bin \\ HelloWorld 1」;但它不會運行 – QuangVinh 2012-03-23 08:25:36

+0

是C:\\ Program Files \\ Java \\ jdk1.6.0_25 \\ bin \\中的HelloWorld.class。 cp選項需要指向類文件的位置。 – GregHNZ 2012-03-23 08:30:39

+0

@QuangVinh類路徑不應該是可執行文件(java.exe),而是編譯的java代碼的位置。即HelloWorld的路徑 – 2012-03-23 08:31:00

0

另一種方法是把你的進程開始信息,以HelloWorld的位置:

ProcessStartInfo pInfo = new ProcessStartInfo(@"C:\Program Files\Java\jdk1.6.0_25\bin\java.exe"); 
pInfo.Arguments = = "HelloWorld"; 
pInfo.WorkingDirectory = @"C:\JavaFiles"; 
pInfo.UseShellExecute = false; 
pInfo.RedirectStandardOutput = true; 

Process javaProc = Process.Start(pInfo); 
string output = javaProc.StandarOutput.ReadToEnd(); 

編輯:我只是意識到你p是一個Process對象。 WorkingDirectoryProcessStartInfo的一個屬性

這是假定存在C:\ JavaFiles \ HelloWorld.class和C:\ JavaFiles \ HelloWorld.java。您還應該遵循Greg的建議並閱讀StandardError,因爲它可以幫助您解決將來出現的問題

+0

謝謝Tung,我沒有p.StartInfo.WorkingDirectory,所以它不起作用。你是越南人嗎?給我你的雅虎成爲朋友:) – QuangVinh 2012-03-23 08:33:15