So I was going into this thinking it would be a simple 1 or 2 line code in order for me to convert the OutputStream into a String so that I can check it better with my logic.
So the code below is what I am currently working with. It works just fine if I just want to write output to the console and that's all. However, I am wanting to store that output as a string.
public static void main(String[] args) throws IOException {
Process p;
try {
p = Runtime.getRuntime().exec("cmd");
new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
stdin.println("cd C:/Local Apps/xxx/xxx/xxxx/eclipse");
stdin.println("lscm login -r https://xxxx.xxxx.xxxx.xxxx:9443/ccm -n xxxx.xxxx.xxx.xxxx -u itsme -P gr^34dbtfgt7y");
stdin.close();
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class SyncPipe implements Runnable {
public SyncPipe(InputStream istrm, OutputStream ostrm) {
istrm_ = istrm;
ostrm_ = ostrm;
}
public void run() {
try {
final byte[] buffer = new byte[1024];
for (int length = 0; (length = istrm_.read(buffer)) != -1;) {
ostrm_.write(buffer, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private final OutputStream ostrm_;
private final InputStream istrm_;
}
I'm wanting to get the data from this:
ostrm_.write(buffer, 0, length);
I've tried all sorts of things I found on google:
String string = new String(ostrm_.toString());
System.out.println(string);
String string = new String(ostrm_.toString("UTF-8"));
System.out.println(string);
final PrintStream blah = new PrintStream(ostrm_);
final String string = blah.toString();
System.out.println(string);
String blah = ostrm_.toString();
System.out.println(string);
byte[] blah = buffer;
String string = blah.toString();
I'm thinking I could use something like OutputStreamWriter but again, I can't seem to get it working. So it would be great if a Java guru can help me solve this issue that seems so easy it's hard....
UPDATE 1 for boot-and-bonnet:
Looks like i finally got it!
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(istrm_));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}