1

I have a Java program that compiles and runs other Java programs. I also have .txt files that have inputs that are fed into the other Java programs.

What I want to know how to do is to capture the output of running with those input files?

user473973
  • 711
  • 2
  • 13
  • 23
  • 2
    [This](http://stackoverflow.com/questions/5389632/capturing-contents-of-standard-output-in-java) other stackoverflow question is probably what you are looking for. – Dennis Meng Oct 08 '13 at 03:55
  • @DavidWallace OP does not know how to do?So posting question here.If some body does not know then its useless to ask what you have tried? – SpringLearner Oct 08 '13 at 04:17
  • 1
    @javaBeginner - Helping people who haven't tried to write the code for themselves isn't what Stack Overflow is for. The idea is to answer specific questions when they get stuck, not to develop code for them from a completely blank slate. Check the FAQ. – Dawood ibn Kareem Oct 08 '13 at 04:23
  • @DavidWallace see even i have also faced similar situation.If something i did not know and i ask here then others leave comment what have you tried.I know OP should have a minimal understanding about the topic.Well If i ask some ideas then this will also help the future users. – SpringLearner Oct 08 '13 at 04:25
  • 1
    @javaBeginner Maybe you should take your point to the Meta site. – Dawood ibn Kareem Oct 08 '13 at 04:38

2 Answers2

4

I'm assuming you're invoking the other program through either ProcessBuilder or Runtime.exec() both return a Process object which has methods getInputStream() and getErrorStream() which allow you to listen on the output and error (stdout, stderr) streams of the other process.

Consider the following code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Test {

    public static void main(String[] args){
        Test t = new Test();

        t.start();
    }

    private void start(){
        String command = //Command to invoke the program

        ProcessBuilder pb = new ProcessBuilder(command);

        try{
            Process p = pb.start();

            InputStream stdout = p.getInputStream();
            InputStream stderr = p.getErrorStream();

            StreamListener stdoutReader = new StreamListener(stdout);
            StreamListener stderrReader = new StreamListener(stderr);

            Thread t_stdoutReader = new Thread(stdoutReader);
            Thread t_stderrReader = new Thread(stderrReader);

            t_stdoutReader.start();
            t_stderrReader.start();
        }catch(IOException n){
            System.err.println("I/O Exception: " + n.getLocalizedMessage());
        }
    }

    private class StreamListener implements Runnable{
        private BufferedReader Reader;
        private boolean Run;

        public StreamListener(InputStream s){
            Reader = new BufferedReader(new InputStreamReader(s));
            Run = true;
        }

        public void run(){
            String line;

            try{
                while(Run && (line = Reader.readLine()) != null){
                    //At this point, a line of the output from the external process has been grabbed. Process it however you want.
                    System.out.println("External Process: " + line);
                }
            }catch(IOException n){
                System.err.println("StreamListener I/O Exception!");
            }
        }
    }
}
initramfs
  • 8,275
  • 2
  • 36
  • 58
0

grasp this example:

  // Try these charsets for encoding text file
  String[] csStrs = {"UTF-8", "UTF-16BE", "UTF-16LE", "UTF-16", "GB2312", "GBK", "BIG5"};
  String outFileExt = "-out.txt";   // Output filenames are "charset-out.txt"

  // Write text file in the specified file encoding charset
  for (int i = 0; i < csStrs.length; ++i) {
     try (OutputStreamWriter out =
             new OutputStreamWriter(
                new FileOutputStream(csStrs[i] + outFileExt), csStrs[i]);
          BufferedWriter bufOut = new BufferedWriter(out)) {  // Buffered for efficiency
        System.out.println(out.getEncoding());  // Print file encoding charset
        bufOut.write(message);
        bufOut.flush();
     } catch (IOException ex) {
        ex.printStackTrace();
     }
  }

  // Read raw bytes from various encoded files
  //   to check how the characters were encoded.
  for (int i = 0; i < csStrs.length; ++i) {
     try (BufferedInputStream in = new BufferedInputStream(  // Buffered for efficiency
             new FileInputStream(csStrs[i] + outFileExt))) {
        System.out.printf("%10s", csStrs[i]);    // Print file encoding charset
        int inByte;
        while ((inByte = in.read()) != -1) {
           System.out.printf("%02X ", inByte);   // Print Hex codes
        }
        System.out.println();
     } catch (IOException ex) {
        ex.printStackTrace();
     }
  }

  // Read text file with character-stream specifying its encoding.
  // The char will be translated from its file encoding charset to
  //   Java internal UCS-2.
  for (int i = 0; i < csStrs.length; ++i) {
     try (InputStreamReader in =
             new InputStreamReader(
                new FileInputStream(csStrs[i] + outFileExt), csStrs[i]);
          BufferedReader bufIn = new BufferedReader(in)) {  // Buffered for efficiency
        System.out.println(in.getEncoding());  // print file encoding charset
        int inChar;
        int count = 0;
        while ((inChar = in.read()) != -1) {
           ++count;
           System.out.printf("[%d]'%c'(%04X) ", count, (char)inChar, inChar);
        }
     System.out.println();
     } catch (IOException ex) {
        ex.printStackTrace();
     }
  }

} }

Rajendra arora
  • 2,186
  • 1
  • 16
  • 23