2015年4月6日 星期一

[ Java 常見問題 ] Get an OutputStream into a String

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):
  1. class StringOutputStream extends OutputStream {  
  2.   
  3.   StringBuilder mBuf;  
  4.   
  5.   public void write(int bytethrows IOException {  
  6.     mBuf.append((charbyte);  
  7.   }  
  8.   
  9.   public String getString() {  
  10.     return mBuf.toString();  
  11.   }  
  12. }  
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:
  1. new String( baos.toByteArray(), codepage );  
or better
  1. baos.toString( codepage );  
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:
  1. package howto;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.PrintStream;  
  5. import java.nio.charset.StandardCharsets;  
  6.   
  7. import flib.util.HexByteKit;  
  8.   
  9. public class OutputStreamToString {  
  10.   
  11.     public static void main(String[] args) throws Exception{  
  12.         MyOutputStream myOS = new MyOutputStream();  
  13.         PrintStream out = new PrintStream(myOS);  
  14.         out.write("Hello".getBytes());  
  15.         System.out.printf("\t[Info] %s\n", myOS.toString());  
  16.         out.write("World".getBytes());  
  17.         System.out.printf("\t[Info] %s\n", myOS.toString());  
  18.         String bytesStr = "E4B8ADE69687"// '中文' byte array in UTF-8 encoding        
  19.         out.write(HexByteKit.Hex2Byte(bytesStr));  
  20.         System.out.printf("\t[Info] %s\n", myOS.toString());  
  21.         System.out.printf("\t[Info] %s\n", myOS.toString(StandardCharsets.UTF_8.toString()));  
  22.     }  
  23.   
  24.     public static class MyOutputStream extends ByteArrayOutputStream  
  25.     {         
  26.         @Override  
  27.         public void write(byte[] b, int off, int len)  
  28.         {  
  29.             System.out.printf("\t[Info] Reading:[ ");  
  30.             for(int i=0; i"%02X ", b[i+off]);  
  31.             System.out.println("]");  
  32.             super.write(b, off, len);  
  33.         }  
  34.     }  
  35. }  
Execution result:
[Info] Reading:[ 48 65 6C 6C 6F ] # 'H' with ASCII code as 48 in hex...
[Info] Hello
[Info] Reading:[ 57 6F 72 6C 64 ]
[Info] HelloWorld
[Info] Reading:[ E4 B8 AD E6 96 87 ]
[Info] HelloWorld中文
[Info] HelloWorld中文
 # The default coding will be UTF-8


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...