0

I have an external program (packaged in a jar) that I want to execute from another Java program, which I do using

Process proc = Runtime.getRuntime().exec(command)

This jar program now returns a sentence as output, which I want to use later on in the program, so I want to convert its output, for which I use the suggestion on using IOUtils I found here.

However

InputStream in = proc.getInputStream(); 
String myString = IOUtils.toString(in, "UTF-8");

only return the first word of the sentence. Is it possible to get the full sentence out of the inputstream?

Community
  • 1
  • 1
MaVe
  • 1,715
  • 5
  • 21
  • 29

1 Answers1

1

If feasible I would take the approach of calling the other JAR's main method immediately. This is not isolated, but you may set the System.out to capture all text.

void startOtherApp(String[] args) {
    final String ENCODING = "UTF-8";
    PrintStream oldOut = System.out;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (PrintStream out = new PrintStream(baos, false, ENCODING)) {
        System.setOut(out);
        OtherJarsMain.main(args);
        out.flush();
        System.setOut(oldOut);
        String s = baos.toString(ENCODING);
        System.out.println("OUTPUT:\n" + s);
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    }
}

To find the main class (here OtherJarsMain), open the jar with 7zip/WinZip or so, and look in /META-INF/MANIFEST.MF. There there is a text line with "Main-Class: aa.bb.OtherJarsMain".

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • It's a compiled jar, so I don't have access to the original java files in order to know what input the original main method takes. – MaVe Jan 16 '14 at 20:39
  • I extended my answer with how `java -jar ...` finds out the main class. – Joop Eggen Jan 16 '14 at 21:05