The other day I needed to read output stream directly into a string, but JDK does not provides us with a stream directly for that. There have been numerous discussions on why and why not we should have this build into the JDK, but this was a case where I did need it and knew the encoding.
My implementation
StringOutputStream backed by ByteArrayOutputStream that simplifies reading of OutputStream directly into string.
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; /** * StringOutputStream backed by ByteArrayOutputStream that simplifies reading of {@link OutputStream} directly into string * @author Grzegorz Bugaj * */ public class StringOutputStream extends OutputStream{ private ByteArrayOutputStream buffer = new ByteArrayOutputStream(); private static final Charset DEFAULT_CHARACTER_SET = Charset.forName("UTF-8"); private Charset characterSet; @Override public void write(int b) throws IOException { buffer.write(b); } @Override public void write(byte[] b) throws IOException { buffer.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { buffer.write(b, off, len); } /** * Get currently set character set if none set default charset of UTF-8 will be used * @return Charaset */ public Charset getCharacterSet() { if(characterSet == null) return DEFAULT_CHARACTER_SET; return characterSet; } public void setCharacterSet(Charset characterSet) { this.characterSet = characterSet; } @Override public String toString() { return new String(buffer.toByteArray(), getCharacterSet()); } } |
Usage Example
/** * Read in given stream into a string * @param stream * @return */ public static String readAsString(InputStream stream) throws IOException{ OutputStream sos = new StringOutputStream(); // Set chunk size to 64K chunk byte[] buffer = new byte[0x10000]; int readLen; while((readLen = stream.read(buffer, 0, buffer.length)) != -1){ sos.write(buffer, 0, readLen); } return sos.toString(); } |