600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > java读取InputStream输入流后输出String字符串

java读取InputStream输入流后输出String字符串

时间:2022-09-23 20:35:26

相关推荐

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("输出异常");}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。