This example shows how to call a C program from Java™ and use input and output streams for interprocess communication.
In this example, the C program writes a string to its standard output stream, and the Java program reads this string and displays it. This example assumes that a library, which is named JAVSAMPLIB, has been created and that the CSAMP1 program has been created in it.
Example 1: CallPgm class
import java.io.*; public class CallPgm { public static void main(String args[]) { Process theProcess = null; BufferedReader inStream = null; System.out.println("CallPgm.main() invoked"); // call the CSAMP1 program try { theProcess = Runtime.getRuntime().exec( "/QSYS.LIB/JAVSAMPLIB.LIB/CSAMP1.PGM"); } catch(IOException e) { System.err.println("Error on exec() method"); e.printStackTrace(); } // read from the called program's standard output stream try { inStream = new BufferedReader(new InputStreamReader (theProcess.getInputStream())); System.out.println(inStream.readLine()); } catch(IOException e) { System.err.println("Error on inStream.readLine()"); e.printStackTrace(); } } // end method } // end class
Example 2: CSAMP1 C Program
#include <stdio.h> #include <stdlib.h> void main(int argc, char* args[]) { /* Convert the string to ASCII at compile time */ #pragma convert(819) printf("Program JAVSAMPLIB/CSAMP1 was invoked\n"); #pragma convert(0) /* Stdout may be buffered, so flush the buffer */ fflush(stdout); }
For more information, see Use input and output streams for interprocess communication.