2016-08-02 31 views
3

我有一個C程序可執行文件,我想從java運行,我也想在運行時爲程序提供輸入。我寫了下面的代碼,但它沒有顯示任何內容。想要運行C程序可以從java執行

Java程序:

public static void main(String[] args) throws IOException { 

    String[] command = {"CMD", "/C", "D:\\TestApp.exe"}; 
    ProcessBuilder probuilder = new ProcessBuilder(command); 

    Process process = probuilder.start(); 

    InputStream is = process.getInputStream(); 
    InputStreamReader isr = new InputStreamReader(is); 
    BufferedReader br = new BufferedReader(isr); 
    String line; 
    System.out.printf("Output of running %s is:\n",Arrays.toString(command)); 
    while ((line = br.readLine()) != null) { 
     System.out.println(line);    
    } 

    try { 
     int exitValue = process.waitFor(); 
     System.out.println("\n\nExit Value is " + exitValue); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
} 

和我的C程序低於:

void main() 
{ 
    int x,y,res; 
    printf("\nEnter the First No:"); 
    scanf("%d",&x); 

    printf("\nEnter the Second No:"); 
    scanf("%d",&y); 

    res = x + y; 
    printf ("\nResult is %d",res); 
    getch(); 
} 

請告訴我的解決方案,Thanx提前。 也告訴我在運行時提供輸入的代碼

+0

在運行時證明輸入您可以通過使用過程中outpuptStream您創建在運行c程序 –

+1

你的代碼process.getOutputStream,寫入這個輸出流,這將作爲輸入提供給c程序 –

+0

你可以使用JNI做更多的事情來直接從java調用你的C函數,而不是從java運行可執行文件。 –

回答

1

C程序需要輸入。寫入過程的標準輸入,寫入process.getOutputStream(),例如:

​​

端接\n是重要的,因爲該過程等待一個新行字符。 .flush()調用也很重要,因爲Java會緩存寫入操作,並且此調用會強制寫出緩衝區的內容。

有了這些行添加到您的代碼,你會得到輸出:

Output of running [/path/to/program] is: 

Enter the First No: 
Enter the Second No: 
Result is 7 


Exit Value is 0