Reputation: 807
I have written a simple code to print the output of console to a BytreArrayOutputStream. I am using JDK 1.7. However when I want the buffer to a String, I can't use the method BytreArrayOutputStream.ToString (String Charset)..
It doesn't have this function. I am using JDk1.7 and it should be supported. I am using Netbean in windoews 7.
PrintStream co1=new PrintStream(new java.io.ByteArrayOutputStream());
System.setOut(co1);
StatsUtil.submit(command);
co1.flush();
co1.close();
co1.toString();//acceptted this but it doesn't give me the stream content
String t=co1.toString("UTF-8");//the compliers give me errors the method doesn't get any string parameter
Any help wold be appreciated.
Upvotes: 1
Views: 7204
Reputation: 521289
You need to call toString()
on the ByteArrayOutputStream
itself, rather than the PrintStream
which wraps it. Try using this code:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream co1 = new PrintStream(baos, "UTF-8");
System.setOut(co1);
StatsUtil.submit(command);
co1.flush();
co1.close();
String t = baos.toString("UTF-8");
Upvotes: 5
Reputation: 1042
It looks like your goal is to collect everything going to System.out via the PrintStream
and get it as a String in the end. Is that correct?
Assuming it is, for now, you are using two different constructs here. PrintStream
and ByteArrayOutputStream
. The PrintStream
is the hose, while the BAOS is the storage tank. Think of the characters being written to as water coming in via the PrintStream
into the BAOS
tank.
When you are done, you are interested in the water in the tank, the hose has nothing in it.
That is why you need to get the bytes out of BAOS via toString.
Upvotes: 1