byte 常用 操作

/** * 低位在前,高位在后 * * @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; }
posted @ 2017-05-05 11:31  fourseasonzl  阅读(606)  评论(0编辑  收藏  举报