Reputation: 5013
I have a situation where I'm looking my Java program to run as BASH script which is turn will run a C++ program.
I am looking to take the output of the C++ program (plain text strings printed to terminal) as input to the Java program.
My first attempt was using the following code to read in input from the terminal, but I wasn't sure how to convert it from user input to automatically taking the C++ input.
Console c;
c = System.console();
if (c == null) {
System.out.println("No console.");
System.exit(1);
}
String data = c.readLine();
I then tried using InputStreamReader
along with redirecting the output of the C++ program:
Java code:
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(System.in));
String htmlLine = null;
while ((htmlLine = input.readLine()) != null) {
System.out.println(htmlLine);
}
}
Command to redirect output:
java -jar program.jar arg1 arg2 arg3 < ./runActivities.sh
However the result of that is that it just prints the contents of runActivities.sh
to the terminal.
Upvotes: 0
Views: 1884
Reputation: 3556
Looks like you have all the Java and C++ code already in place. The missing puzzle piece seems to be the shell redirection. You should consult the manual of the shell you are using and look for redirection. In case you are using bash shell the redirection should look like this:
$ ./runActivities.sh | java -jar program.jar arg1 arg2 arg3
Upvotes: 5
Reputation: 6414
You could use Runtime.getRuntime().exec("yourCommand") function from java, it will return a Process object which has an input, output and err streams, You can use those Streams to send and receive data to and from your Porcess.
Process p = Runtime.getRuntime().exec("yourCommand");
InputStream is = p.getInputStream();
// you con now read from inputStream, it is the output of your programm in C++
Upvotes: 1