流读成字符串和字节数组
2015-12-16 00:00
134 查看
摘要: 流读成字符串和字节数组
public class StreamUtil { private static final Logger logger = LoggerFactory.getLogger(StreamUtil.class); public static final int DEFAULT_BUFFER_SIZE = 2048; /** * 将输入流中信息读取成字符串, 缓冲默认使用2kb * * @param in * @return */ public static byte[] readByteArray(InputStream in) { return readByteArray(in, DEFAULT_BUFFER_SIZE); } /** * 将输入流中信息读取成字节数组 * * @param in * @param bufferSize * 读取流时的字节缓冲大小 * @return */ public static byte[] readByteArray(InputStream in, int bufferSize) { BufferedInputStream bis = new BufferedInputStream(in); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[bufferSize]; int i = 0; try { while ((i = bis.read(buf)) != -1) { bos.write(buf, 0, i); } return bos.toByteArray(); } catch (IOException e) { logger.error(e.getMessage()); e.printStackTrace(); } finally { try { if (bos != null) { bos.close(); } if (bis != null) { bis.close(); } } catch (IOException e) { logger.error(e.getMessage()); e.printStackTrace(); } } return null; } /** * 将输入流中信息读取成字符串 * * @param in * @param bufferSize * 读取流时的字节缓冲大小 * @return */ public static String readString(InputStream in, int bufferSize) { BufferedInputStream bis = new BufferedInputStream(in); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[bufferSize]; int i = 0; try { while ((i = bis.read(buf)) != -1) { bos.write(buf, 0, i); } return bos.toString("UTF-8"); } catch (IOException e) { logger.error(e.getMessage()); e.printStackTrace(); } finally { try { if (bos != null) { bos.close(); } if (bis != null) { bis.close(); } } catch (IOException e) { logger.error(e.getMessage()); e.printStackTrace(); } } return null; } /** * 将输入流中信息读取成字符串, 缓冲默认使用2kb * * @param in * @return */ public static String readString(InputStream in) { return readString(in, DEFAULT_BUFFER_SIZE); } /** * 将字符串写入流中 * * @param out * @param data */ public static void writeString(OutputStream out, String data) { BufferedOutputStream bout = new BufferedOutputStream(out); try { bout.write(data.getBytes()); } catch (IOException e) { logger.error(e.getMessage()); e.printStackTrace(); } finally { try { if (bout != null) { bout.flush(); bout.close(); } } catch (IOException e) { logger.error(e.getMessage()); e.printStackTrace(); } } } }
相关文章推荐
- 将java集合转换成map
- Gson详解:Java对象与JSON相互转换的利器
- 重要的是坚持
- Sublime Text 学习笔记
- ios端与java之间的RSA算法加密
- JavaScript节点
- JS的事件监听机制
- 用Kettle的一套流程完成对整个数据库迁移
- 怎样将iMindMap中导图以表格形式导出
- ios GCD多线程
- DIY 微信HD版共享
- Node.js开发指南 学习日志 3.3.3创建包
- hosts2015-12-16
- 批量修改扩展名
- servlet
- 给低价手游代充商家的建议:尽早寻求其他出路
- 网站流量变现最新方法 轻轻松松月入百万
- Android源码之陌陌项目源码
- 高仿人人网客户端安卓源码项目
- 似于印象笔记Evernote生活类iOS应用源码