java读取InputStream输入流后输出String字符串
生活随笔
收集整理的這篇文章主要介紹了
java读取InputStream输入流后输出String字符串
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
為什么80%的碼農都做不了架構師?>>> ??
功能:例子中輸出字符編碼為GBK,輸入流保護 50KB,讀取InputStream輸入流后輸出String字符串。
private static final String DEFAULT_ENCODING = "GBK";//編碼private static final int PROTECTED_LENGTH = 51200;// 輸入流保護 50KBpublic String readInfoStream(InputStream input) throws Exception {if (input == null) {throw new Exception("輸入流為null");}//字節數組byte[] bcache = new byte[2048];int readSize = 0;//每次讀取的字節長度int totalSize = 0;//總字節長度ByteArrayOutputStream infoStream = new ByteArrayOutputStream();try {//一次性讀取2048字節while ((readSize = input.read(bcache)) > 0) {totalSize += readSize;if (totalSize > PROTECTED_LENGTH) {throw new Exception("輸入流超出50K大小限制");}//將bcache中讀取的input數據寫入infoStreaminfoStream.write(bcache,0,readSize);}} catch (IOException e1) {throw new Exception("輸入流讀取異常");} finally {try {//輸入流關閉input.close();} catch (IOException e) {throw new Exception("輸入流關閉異常");}}try {return infoStream.toString(DEFAULT_ENCODING);} catch (UnsupportedEncodingException e) {throw new Exception("輸出異常");}}轉載于:https://my.oschina.net/zjcx/blog/679611
總結
以上是生活随笔為你收集整理的java读取InputStream输入流后输出String字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java中怎样创建线程安全的方法
- 下一篇: Debian Linux下的Python