Tuesday, 20 January 2015

Execute shell commands using Java Runtime in PeopleCode

Java Runtime class can be used to execute shell commands in PeopleCode and capture the output. The example below executes UNIX grep command to count the number of non-blank rows in a file and store the output into a variable.

   Local string &cmd;
   Local number &fileRowCount;
   Local JavaObject &command, &runtime, &process, &inputStreamReader, &bufferedReader;
  
   &cmd = "grep -v ^$ " | &fileName | " | wc -l";
  
   &command = CreateJavaObject("java.lang.String[]", "sh", "-c", &cmd);
   &runtime = GetJavaClass("java.lang.Runtime").getRuntime();
   &process = &runtime.exec(&command);
  
   &inputStreamReader = CreateJavaObject("java.io.InputStreamReader", &process.getInputStream());
   &bufferedReader = CreateJavaObject("java.io.BufferedReader", &inputStreamReader);
   &fileRowCount = &bufferedReader.readLine();

No comments:

Post a Comment