Java 字节的常用封装 | 文末有福利

640?wx_fmt=jpeg


一. Java 的字节

byte (字节) 是 Java 中的基本数据类型,一个 byte 包含8个 bit(位),byte 的取值范围是-128到+127。

byte 跟 Java 其他基本类型的关系:

基本类型所占字节数备注
byte1
short2
int4
long8
char2
float4
double8
boolean1、4《Java虚拟机规范》给出了4个字节,和boolean数组1个字节的定义,具体还要看虚拟机实现是否按照规范来

二. 常用封装

由于工作关系,我封装了一个操作字节的库

github 地址:https://github.com/fengzhizi715/bytekit

2.1 bytekit 的特点:

  • 支持多种方式创建 Bytes

  • 支持字节数组、ByteBuffer 的操作

  • 支持 Immutable 对象:ByteArrayBytes、ByteBufferBytes

  • 支持 Transformer: 内置 copy、contact、reverse、xor、and、or、not,也支持自定义 Transformer

  • 支持 Hash: 内置 md5、sha1、sha256

  • 支持转换成16进制字符串

  • 支持 mmap 常用读写操作:readByte/writeByte、readBytes/writeBytes、readInt/writeInt、readLong/writeLong、readDouble/writeDouble、readObject/writeObject

  • 支持对象的序列化、反序列化、深拷贝

  • 不依赖任何第三方库


    640?wx_fmt=png

Bytes 是一个接口,它有三个实现类:ByteArrayBytes、ByteBufferBytes、MmapBytes。其中,前面两个实现类是 Immutable 对象。

2.2 支持 Immutable 对象

Immutable 对象(不可变对象),即对象一旦被创建它的状态(对象的数据,也即对象属性值)就不能改变。

它的优点:

  • 构造、测试和使用都很简单

  • 线程安全

  • 当用作类的属性时不需要保护性拷贝

  • 可以很好的用作Map键值和Set元素

2.3 支持 Hash 加密

对 Bytes 中的 byte[] 进行加密。在 Bytes 接口中,包含下面的默认函数:

 
 
  1.    /**

  2.     * 使用md5加密

  3.     * @return

  4.     */

  5.    default Bytes md5() {


  6.        return transform(new MessageDigestTransformer("MD5"));

  7.    }


  8.    /**

  9.     * 使用sha1加密

  10.     * @return

  11.     */

  12.    default Bytes sha1() {


  13.        return transform(new MessageDigestTransformer("SHA-1"));

  14.    }


  15.    /**

  16.     * 使用sha256加密

  17.     * @return

  18.     */

  19.    default Bytes sha256() {


  20.        return transform(new MessageDigestTransformer("SHA-256"));

  21.    }

进行单元测试:

 
 
  1.    @Test

  2.    public void testHash() {


  3.        Bytes bytes = ByteArrayBytes.create("hello world");


  4.        assertEquals("5eb63bbbe01eeed093cb22bb8f5acdc3", bytes.md5().toHexString());

  5.        assertEquals("2aae6c35c94fcfb415dbe95f408b9ce91ee846ed", bytes.sha1().toHexString());

  6.        assertEquals("b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9", bytes.sha256().toHexString());

  7.    }

2.4 序列化、反序列化、深拷贝

支持对象的序列化、反序列化以及深拷贝。在 Bytes 接口中,包含下面的静态函数:

 
 
  1.    /**

  2.     * 序列化对象,转换成字节数组

  3.     * @param obj

  4.     * @return

  5.     */

  6.    static byte[] serialize(Object obj) {

  7.        byte[] result = null;

  8.        ByteArrayOutputStream fos = null;


  9.        try {

  10.            fos = new ByteArrayOutputStream();

  11.            ObjectOutputStream o = new ObjectOutputStream(fos);

  12.            o.writeObject(obj);

  13.            result = fos.toByteArray();

  14.        } catch (IOException e) {

  15.            System.err.println(e);

  16.        } finally {


  17.            IOUtils.closeQuietly(fos);

  18.        }


  19.        return result;

  20.    }


  21.    /**

  22.     * 反序列化字节数字,转换成对象

  23.     * @param bytes

  24.     * @return

  25.     */

  26.    static Object deserialize(byte[] bytes) {

  27.        InputStream fis = null;


  28.        try {

  29.            fis = new ByteArrayInputStream(bytes);

  30.            ObjectInputStream o = new ObjectInputStream(fis);

  31.            return o.readObject();

  32.        } catch (IOException e) {

  33.            System.err.println(e);

  34.        } catch (ClassNotFoundException e) {

  35.            System.err.println(e);

  36.        } finally {


  37.            IOUtils.closeQuietly(fis);

  38.        }


  39.        return null;

  40.    }


  41.    /**

  42.     * 通过序列化/反序列化实现对象的深拷贝

  43.     * @param obj

  44.     * @param <T>

  45.     * @return

  46.     */

  47.    static <T> T cloneObject(T obj) {


  48.        return (T) deserialize(serialize(obj));

  49.    }

进行单元测试:

 
 
  1.    @Test

  2.    public void testSerializeAndDeserialize() {


  3.        User u = new User();

  4.        u.name = "tony";

  5.        u.password = "123456";


  6.        byte[] bytes = Bytes.serialize(u);


  7.        User newUser = (User)Bytes.deserialize(bytes);

  8.        assertEquals(u.name, newUser.name);

  9.        assertEquals(u.password,newUser.password);

  10.    }


  11.    @Test

  12.    public void testDeepCopy() {


  13.        User u = new User();

  14.        u.name = "tony";

  15.        u.password = "123456";


  16.        User newUser = Bytes.cloneObject(u);

  17.        System.out.println(u);

  18.        System.out.println(newUser);

  19.        assertNotSame(u,newUser);

  20.        assertNotSame(u.name,newUser.name);

  21.    }

testDeepCopy() 执行后,u 和 newUser 地址的不同,u.name 和 newUser.name 指向的内存地址也不同。

 
 
  1. com.safframework.bytekit.domain.User@2b05039f

  2. com.safframework.bytekit.domain.User@17d10166

2.5 copy、contact、reverse

copy、contact、reverse 都是采用 Transformer 的方式。在 AbstractBytes 类中,包含下面的函数:

 
 
  1.    @Override

  2.    public Bytes copy() {


  3.        return transform(new CopyTransformer(0, size()));

  4.    }


  5.    @Override

  6.    public Bytes copy(int offset, int length) {


  7.        return transform(new CopyTransformer(offset, length));

  8.    }


  9.    @Override

  10.    public Bytes contact(byte[] bytes) {


  11.        return transform(new ConcatTransformer(bytes));

  12.    }


  13.    @Override

  14.    public Bytes reverse() {


  15.        return transform(new ReverseTransformer());

  16.    }

进行单元测试:

 
 
  1.    @Test

  2.    public void testContact() {


  3.        Bytes bytes = ByteBufferBytes.create("hello world").contact(" tony".getBytes());


  4.        assertEquals(bytes.toString(), "hello world tony");

  5.    }


  6.    @Test

  7.    public void testCopy() {


  8.        Bytes bytes = ByteBufferBytes.create("hello world").contact(" tony".getBytes());


  9.        assertEquals(bytes.toString(), bytes.copy().toString());

  10.    }


  11.    @Test

  12.    public void testReverse() {


  13.        Bytes bytes = ByteBufferBytes.create("hello world").contact(" tony".getBytes());


  14.        assertEquals(bytes.toString(), bytes.reverse().reverse().toString());

  15.    }

2.6 位操作

xor、and、or、not 也是采用 Transformer 的方式。在 AbstractBytes 类中,包含下面的函数:

 
 
  1.    @Override

  2.    public Bytes xor(byte[] bytes) {


  3.        return transform(new BitWiseOperatorTransformer(bytes,BitWiseOperatorTransformer.Mode.XOR));

  4.    }


  5.    @Override

  6.    public Bytes and(byte[] bytes) {


  7.        return transform(new BitWiseOperatorTransformer(bytes, BitWiseOperatorTransformer.Mode.AND));

  8.    }


  9.    @Override

  10.    public Bytes or(byte[] bytes) {


  11.        return transform(new BitWiseOperatorTransformer(bytes, BitWiseOperatorTransformer.Mode.OR));

  12.    }


  13.    @Override

  14.    public Bytes not(byte[] bytes) {


  15.        return transform(new BitWiseOperatorTransformer(bytes, BitWiseOperatorTransformer.Mode.NOT));

  16.    }

进行单元测试:

 
 
  1.    @Test

  2.    public void testBitWise() {


  3.        ByteBufferBytes bytes = (ByteBufferBytes)ByteBufferBytes.create("hello world").contact(" tony".getBytes());


  4.        assertEquals(bytes.toString(), bytes.and(bytes.toByteArray()).or(bytes.toByteArray()).toString());

  5.        assertEquals(bytes.toString(), bytes.not(bytes.toByteArray()).not(bytes.toByteArray()).toString());

  6.        assertEquals(bytes.toString(), bytes.xor(bytes.toByteArray()).xor(bytes.toByteArray()).toString()); //两次xor 返回本身

  7.    }

2.7 Base64 编码、解码

 
 
  1.    @Test

  2.    public void testBase64() {


  3.        ByteBufferBytes bytes = (ByteBufferBytes)ByteBufferBytes.create("hello world").contact(" tony".getBytes());


  4.        String base64 = new String(bytes.encodeBase64());

  5.        assertEquals(bytes.toString(), new String(Bytes.parseBase64(base64)));

  6.    }

2.8 Bytes 转换成字节数组

 
 
  1.    @Test

  2.    public void testToByteArray() {


  3.        Bytes bytes = ByteBufferBytes.create("hello world").contact(" tony".getBytes());


  4.        assertEquals(bytes.toString(), new String(bytes.toByteArray()));

  5.    }

三. mmap 的操作

Linux 的 mmap 是一种内存映射文件的方法。

mmap将一个文件或者其它对象映射进内存。文件被映射到多个页上,如果文件的大小不是所有页的大小之和,最后一个页不被使用的空间将会清零。mmap在用户空间映射调用系统中作用很大。 mmap系统调用是将一个打开的文件映射到进程的用户空间,mmap系统调用使得进程之间通过映射同一个普通文件实现共享内存。普通文件被映射到进程地址空间后,进程可以像访问普通内存一样对文件进行访问,不必再调用read()、write()等操作。

 
 
  1. import com.safframework.bytekit.domain.User;

  2. import com.safframework.bytekit.jdk.mmap.MmapBytes;

  3. import org.junit.After;

  4. import org.junit.Before;

  5. import org.junit.Test;


  6. import static junit.framework.TestCase.assertEquals;


  7. /**

  8. * Created by tony on 2018-12-24.

  9. */

  10. public class MmapBytesTest {


  11.    private MmapBytes mmapBytes;

  12.    private String file;


  13.    @Before

  14.    public void setUp() {


  15.        file = "test";

  16.        mmapBytes = new MmapBytes(file, (long) 1024 * 10); // 10M

  17.    }


  18.    @Test

  19.    public void testWriteAndRead() throws Exception {


  20.        mmapBytes.writeInt(12);

  21.        mmapBytes.writeInt(34);

  22.        mmapBytes.writeByte((byte) 5);

  23.        mmapBytes.writeBytes(("this is tony").getBytes());

  24.        mmapBytes.writeLong(6666L);

  25.        mmapBytes.writeDouble(3.14d);


  26.        assertEquals(12, mmapBytes.readInt());

  27.        assertEquals(34, mmapBytes.readInt());

  28.        assertEquals((byte) 5, mmapBytes.readByte());

  29.        assertEquals("this is tony", new String(mmapBytes.readBytes(12)));

  30.        assertEquals(6666L, mmapBytes.readLong());

  31.        assertEquals(3.14d, mmapBytes.readDouble());

  32.    }


  33.    @Test

  34.    public void testObject() throws Exception {


  35.        User u = new User();

  36.        u.name = "tony";

  37.        u.password = "123456";


  38.        mmapBytes.writeObject(u);


  39.        User temp = (User)mmapBytes.readObject(117);


  40.        assertEquals(u.name, temp.name);

  41.        assertEquals(u.password, temp.password);

  42.    }


  43.    @Test

  44.    public void testFree() throws Exception {


  45.        mmapBytes.writeInt(12);

  46.        mmapBytes.writeInt(34);

  47.        mmapBytes.writeByte((byte) 5);


  48.        mmapBytes.free();


  49.        mmapBytes = new MmapBytes(file, (long) 1024 * 10); // 10M

  50.        mmapBytes.writeInt(67);


  51.        assertEquals(67, mmapBytes.readInt());

  52.    }


  53.    @After

  54.    public void tearDown() {

  55.        mmapBytes.free();

  56.    }

  57. }

四. 总结

bytekit 是一个(),不依赖任何第三方库。它封装了字节数组、ByteBuffer 的操作,支持 mmap 常用的读写。

当然,它还可以封装 protobuf 的 ByteString 或者 Android 中的 Parcel,只需实现 Bytes 接口即可。

参考资料:

https://www.jianshu.com/p/2f663dc820d0


福利时间:

本人的 Kotlin 小册

(https://juejin.im/book/5af1c5ee6fb9a07a9f018368)

已在掘金预售,圣诞节送若干5折优惠券,可以在本文的底部留言向小编索取。

640?wx_fmt=png



关注【Java与Android技术栈】

更多精彩内容请关注扫码

640?wx_fmt=jpeg



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值