Reputation: 107
How to run c execute file with user input in Java Runtime().exec()
. Without user
input in my c program execute file runs in Runtime().exec()
:
For example: Below c program if n is predefined and it's execute file runs in java runtime()...If n is a user input how to run the execute file?
#include <stdio.h>
#include <time.h>
#include <unistd.h>
int main()
{
setbuf(stdout, NULL); //set buffer null
int i,n;
scanf("%d",&n);
for(i=0;i<=n;i++)
{
printf("%d\n",i);
sleep(1); //delay
}
} //main
Java code ....
import java.io.*;
import java.lang.Runtime;
import java.lang.*;
import java.io.File;
import java.util.Timer;
import java.util.TimerTask;
public class run3
{
public static void main(String[] args)
{
try
{
String[] cmd = {"file path"};
Process p = java.lang.Runtime.getRuntime().exec(cmd);
String s;
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
while ((s = stdInput.readLine()) != null)
{ System.out.println(s); }
System.out.println("Done.");
}//try
catch (IOException ex)
{ ex.printStackTrace(); }
} //void
} //main
Upvotes: 3
Views: 2207
Reputation: 718738
There are various ways to do this, depending on exactly what you are trying to achieve:
The simplest way to do this would be to pass n
as a command line argument.
You could have the C program read n
from its standard input ... and write to it from the Java side using the Process
object's getOutputStream
method.
You could have the C program open "/dev/console" or "/dev/tty" and read n
from there. On Windows I believe you can do this in other ways.
OK. Given that, you just need to call p.getInputStream()
, write the input to that stream, and close it ... before attempting to read the command's output.
Upvotes: 1