码迷,mamicode.com
首页 > 其他好文 > 详细

byte 常用 操作

时间:2017-05-05 11:44:48      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:byte   读取   ror   throws   close   开始   异常   下标   字节   

/** * 低位在前,高位在后 * * @param data * @return */ private byte[] intToBytes(int value) { byte[] src = new byte[4]; src[3] = (byte) ((value >> 24) & 0xFF); src[2] = (byte) ((value >> 16) & 0xFF); src[1] = (byte) ((value >> 8) & 0xFF); src[0] = (byte) (value & 0xFF); return src; } public int bytesToInt(byte[] src) { int value; value = (int) ((src[0] & 0xFF) | ((src[1] & 0xFF)<<8) | ((src[2] & 0xFF)<<16) | ((src[3] & 0xFF)<<24)); return value; } /** * 对象转byte * * @param obj * @return */ public byte[] objectToByte(Object obj) { byte[] bytes = null; ByteArrayOutputStream byteOutput = null; ObjectOutputStream objOutput = null; try { // object to bytearray byteOutput = new ByteArrayOutputStream(); objOutput = new ObjectOutputStream(byteOutput); objOutput.writeObject(obj); bytes = byteOutput.toByteArray(); byteOutput.close(); objOutput.close(); } catch (Exception e) { logger.error("ObjectToByte异常", e); } finally { try { if (byteOutput != null) { byteOutput.close(); } if (objOutput != null) { objOutput.close(); } } catch (IOException e) { logger.error("ObjectToByte异常", e); } } return bytes; } /** * byte 转对象 * * @param bytes * @return */ public Object byteToObject(byte[] bytes) throws Exception { Object obj = null; ByteArrayInputStream byteInput = null; ObjectInputStream objectInput = null; try { // bytearray to object if (bytes != null) { byteInput = new ByteArrayInputStream(bytes); objectInput = new ObjectInputStream(byteInput); obj = objectInput.readObject(); byteInput.close(); objectInput.close(); } } catch (Exception e) { logger.error("ByteToObject异常", e); throw e; } finally { try { if (byteInput != null) { byteInput.close(); } if (objectInput != null) { objectInput.close(); } } catch (IOException e) { logger.error("byteToObject异常", e); } } return obj; } public byte[] streamToBytes(InputStream inputStream, int len) { /** * inputStream.read(要复制到得字节数组,起始位置下标,要复制的长度) * 该方法读取后input的下标会自动的后移,下次读取的时候还是从上次读取后移动到的下标开始读取 所以每次读取后就不需要在制定起始的下标了 */ byte[] bytes = new byte[len]; try { inputStream.read(bytes, 0, len); } catch (IOException e) { logger.error(ConstantUtils.LOG_EXCEPTION, e); } return bytes; }

byte 常用 操作

标签:byte   读取   ror   throws   close   开始   异常   下标   字节   

原文地址:http://www.cnblogs.com/fourseasonzl/p/6812136.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!