Source From Here
Question
What's the best way to pipe the output from an java.io.OutputStream to a String in Java?
I'm considering writing a class like this (untested):
But is there a better way? I only want to run a test!
How-To
I would use a ByteArrayOutputStream. And on finish you can call:
or better
For the String constructor the codepage can be a String or an instance of
java.nio.charset.Charset. A possible value isjava.nio.charset.StandardCharsets.UTF_8. Below is sample code:
Execution result:
Question
What's the best way to pipe the output from an java.io.OutputStream to a String in Java?
I'm considering writing a class like this (untested):
- class StringOutputStream extends OutputStream {
- StringBuilder mBuf;
- public void write(int byte) throws IOException {
- mBuf.append((char) byte);
- }
- public String getString() {
- return mBuf.toString();
- }
- }
How-To
I would use a ByteArrayOutputStream. And on finish you can call:
- new String( baos.toByteArray(), codepage );
- baos.toString( codepage );
- package howto;
- import java.io.ByteArrayOutputStream;
- import java.io.PrintStream;
- import java.nio.charset.StandardCharsets;
- import flib.util.HexByteKit;
- public class OutputStreamToString {
- public static void main(String[] args) throws Exception{
- MyOutputStream myOS = new MyOutputStream();
- PrintStream out = new PrintStream(myOS);
- out.write("Hello".getBytes());
- System.out.printf("\t[Info] %s\n", myOS.toString());
- out.write("World".getBytes());
- System.out.printf("\t[Info] %s\n", myOS.toString());
- String bytesStr = "E4B8ADE69687"; // '中文' byte array in UTF-8 encoding
- out.write(HexByteKit.Hex2Byte(bytesStr));
- System.out.printf("\t[Info] %s\n", myOS.toString());
- System.out.printf("\t[Info] %s\n", myOS.toString(StandardCharsets.UTF_8.toString()));
- }
- public static class MyOutputStream extends ByteArrayOutputStream
- {
- @Override
- public void write(byte[] b, int off, int len)
- {
- System.out.printf("\t[Info] Reading:[ ");
- for(int i=0; i
"%02X ", b[i+off]); - System.out.println("]");
- super.write(b, off, len);
- }
- }
- }
沒有留言:
張貼留言