Java 字节的常用封装
一. Java 的字节
byte (字节) 是 Java 中的基本数据类型,一个 byte 包含8个 bit(位),byte 的取值范围是-128到+127。
byte 跟 Java 其他基本类型的关系:
二. 常用封装
由于工作关系,我封装了一个操作字节的库
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
支持对象的序列化、反序列化、深拷贝
不依赖任何第三方库
Bytes 是一个接口,它有三个实现类:ByteArrayBytes、ByteBufferBytes、MmapBytes。其中,前面两个实现类是 Immutable 对象。
2.2 支持 Immutable 对象
Immutable 对象(不可变对象),即对象一旦被创建它的状态(对象的数据,也即对象属性值)就不能改变。
它的优点:
构造、测试和使用都很简单
线程安全
当用作类的属性时不需要保护性拷贝
可以很好的用作Map键值和Set元素
2.3 支持 Hash 加密
对 Bytes 中的 byte[] 进行加密。在 Bytes 接口中,包含下面的默认函数:
/**
* 使用md5加密
* @return
*/
default Bytes md5() {
return transform(new MessageDigestTransformer(MD5));
}
/**
* 使用sha1加密
* @return
*/
default Bytes sha1() {
return transform(new MessageDigestTransformer(SHA-1));
}
/**
* 使用sha256加密
* @return
*/
default Bytes sha256() {
return transform(new MessageDigestTransformer(SHA-256));
}
进行单元测试:
@Test
public void testHash() {
Bytes bytes = ByteArrayBytes.create(hello world);
assertEquals(5eb63bbbe01eeed093cb22bb8f5acdc3, bytes.md5().toHexString());
assertEquals(2aae6c35c94fcfb415dbe95f408b9ce91ee846ed, bytes.sha1().toHexString());
assertEquals(b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9, bytes.sha256().toHexString());
}
2.4 序列化、反序列化、深拷贝
支持对象的序列化、反序列化以及深拷贝。在 Bytes 接口中,包含下面的静态函数:
/**
* 序列化对象,转换成字节数组
* @param obj
* @return
*/
static byte[] serialize(Object obj) {
byte[] result = null;
ByteArrayOutputStream fos = null;
try {
fos = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(fos);
o.writeObject(obj);
result = fos.toByteArray();
} catch (IOException e) {
System.err.println(e);
} finally {
IOUtils.closeQuietly(fos);
}
return result;
}
/**
* 反序列化字节数字,转换成对象
* @param bytes
* @return
*/
static Object deserialize(byte[] bytes) {
InputStream fis = null;
try {
fis = new ByteArrayInputStream(bytes);
ObjectInputStream o = new ObjectInputStream(fis);
return o.readObject();
} catch (IOException e) {
System.err.println(e);
} catch (ClassNotFoundException e) {
System.err.println(e);
} finally {
IOUtils.closeQuietly(fis);
}
return null;
}
/**
* 通过序列化/反序列化实现对象的深拷贝
* @param obj
* @param
* @return
*/
staticT cloneObject(T obj) {
return (T) deserialize(serialize(obj));
}
进行单元测试:
@Test
public void testSerializeAndDeserialize() {
User u = new User();
u.name = tony;
u.password = 123456;
byte[] bytes = Bytes.serialize(u);
User newUser = (User)Bytes.deserialize(bytes);
assertEquals(u.name, newUser.name);
assertEquals(u.password,newUser.password);
}
@Test
public void testDeepCopy() {
User u = new User();
u.name = tony;
u.password = 123456;
User newUser = Bytes.cloneObject(u);
System.out.println(u);
System.out.println(newUser);
assertNotSame(u,newUser);
assertNotSame(u.name,newUser.name);
}
testDeepCopy() 执行后,u 和 newUser 地址的不同,u.name 和 newUser.name 指向的内存地址也不同。
com.safframework.bytekit.domain.User@2b05039f
com.safframework.bytekit.domain.User@17d10166
2.5 copy、contact、reverse
copy、contact、reverse 都是采用 Transformer 的方式。在 AbstractBytes 类中,包含下面的函数:
@Override
public Bytes copy() {
return transform(new CopyTransformer(0, size()));
}
@Override
public Bytes copy(int offset, int length) {
return transform(new CopyTransformer(offset, length));
}
@Override
public Bytes contact(byte[] bytes) {
return transform(new ConcatTransformer(bytes));
}
@Override
public Bytes reverse() {
return transform(new ReverseTransformer());
}
进行单元测试:
@Test
public void testContact() {
Bytes bytes = ByteBufferBytes.create(hello world).contact( tony.getBytes());
assertEquals(bytes.toString(), hello world tony);
}
@Test
public void testCopy() {
Bytes bytes = ByteBufferBytes.create(hello world).contact( tony.getBytes());
assertEquals(bytes.toString(), bytes.copy().toString());
}
@Test
public void testReverse() {
Bytes bytes = ByteBufferBytes.create(hello world).contact( tony.getBytes());
assertEquals(bytes.toString(), bytes.reverse().reverse().toString());
}
2.6 位操作
xor、and、or、not 也是采用 Transformer 的方式。在 AbstractBytes 类中,包含下面的函数:
@Override
public Bytes xor(byte[] bytes) {
return transform(new BitWiseOperatorTransformer(bytes,BitWiseOperatorTransformer.Mode.XOR));
}
@Override
public Bytes and(byte[] bytes) {
return transform(new BitWiseOperatorTransformer(bytes, BitWiseOperatorTransformer.Mode.AND));
}
@Override
public Bytes or(byte[] bytes) {
return transform(new BitWiseOperatorTransformer(bytes, BitWiseOperatorTransformer.Mode.OR));
}
@Override
public Bytes not(byte[] bytes) {
return transform(new BitWiseOperatorTransformer(bytes, BitWiseOperatorTransformer.Mode.NOT));
}
进行单元测试:
@Test
public void testBitWise() {
ByteBufferBytes bytes = (ByteBufferBytes)ByteBufferBytes.create(hello world).contact( tony.getBytes());
assertEquals(bytes.toString(), bytes.and(bytes.toByteArray()).or(bytes.toByteArray()).toString());
assertEquals(bytes.toString(), bytes.not(bytes.toByteArray()).not(bytes.toByteArray()).toString());
assertEquals(bytes.toString(), bytes.xor(bytes.toByteArray()).xor(bytes.toByteArray()).toString()); //两次xor 返回本身
}
2.7 Base64 编码、解码
@Test
public void testBase64() {
ByteBufferBytes bytes = (ByteBufferBytes)ByteBufferBytes.create(hello world).contact( tony.getBytes());
String base64 = new String(bytes.encodeBase64());
assertEquals(bytes.toString(), new String(Bytes.parseBase64(base64)));
}
2.8 Bytes 转换成字节数组
@Test
public void testToByteArray() {
Bytes bytes = ByteBufferBytes.create(hello world).contact( tony.getBytes());
assertEquals(bytes.toString(), new String(bytes.toByteArray()));
}
三. mmap 的操作
Linux 的 mmap 是一种内存映射文件的方法。
mmap将一个文件或者其它对象映射进内存。文件被映射到多个页上,如果文件的大小不是所有页的大小之和,最后一个页不被使用的空间将会清零。mmap在用户空间映射调用系统中作用很大。 mmap系统调用是将一个打开的文件映射到进程的用户空间,mmap系统调用使得进程之间通过映射同一个普通文件实现共享内存。普通文件被映射到进程地址空间后,进程可以像访问普通内存一样对文件进行访问,不必再调用read()、write()等操作。
import com.safframework.bytekit.domain.User;
import com.safframework.bytekit.jdk.mmap.MmapBytes;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
/**
* Created by tony on 2018-12-24.
*/
public class MmapBytesTest {
private MmapBytes mmapBytes;
private String file;
@Before
public void setUp() {
file = test;
mmapBytes = new MmapBytes(file, (long) 1024 * 10); // 10M
}
@Test
public void testWriteAndRead() throws Exception {
mmapBytes.writeInt(12);
mmapBytes.writeInt(34);
mmapBytes.writeByte((byte) 5);
mmapBytes.writeBytes((this is tony).getBytes());
mmapBytes.writeLong(6666L);
mmapBytes.writeDouble(3.14d);
assertEquals(12, mmapBytes.readInt());
assertEquals(34, mmapBytes.readInt());
assertEquals((byte) 5, mmapBytes.readByte());
assertEquals(this is tony, new String(mmapBytes.readBytes(12)));
assertEquals(6666L, mmapBytes.readLong());
assertEquals(3.14d, mmapBytes.readDouble());
}
@Test
public void testObject() throws Exception {
User u = new User();
u.name = tony;
u.password = 123456;
mmapBytes.writeObject(u);
User temp = (User)mmapBytes.readObject(117);
assertEquals(u.name, temp.name);
assertEquals(u.password, temp.password);
}
@Test
public void testFree() throws Exception {
mmapBytes.writeInt(12);
mmapBytes.writeInt(34);
mmapBytes.writeByte((byte) 5);
mmapBytes.free();
mmapBytes = new MmapBytes(file, (long) 1024 * 10); // 10M
mmapBytes.writeInt(67);
assertEquals(67, mmapBytes.readInt());
}
@After
public void tearDown() {
mmapBytes.free();
}
}
四. 总结
bytekit 是一个操作字节的工具库,不依赖任何第三方库。它封装了字节数组、ByteBuffer 的操作,支持 mmap 常用的读写。
当然,它还可以封装 protobuf 的 ByteString 或者 Android 中的 Parcel,只需实现 Bytes 接口即可。
Java 字节的常用封装的更多相关文章
- Java字节码操纵框架ASM小试
本文主要内容: ASM是什么 JVM指令 Java字节码文件 ASM编程模型 ASM示例 参考资料汇总 JVM详细指令 ASM是什么 ASM是一个Java字节码操纵框架,它能被用来动态生成类或者增强既 ...
- java程序员常用的八个工具
以下这8个工具,从代码构建到错误挤压,覆盖Java开发的全域.学习这些工具可以帮助你改善代码质量,成为一个更高效的Java开发人员. 1.Eclipse 尽管IntelliJ IDEA.NetBean ...
- Java基础和常用框架的面试题
前言 最近学校也催着找工作了,于是刷了一些面试题,学习了几篇大佬优秀的博客,总结了一些自认为重要的知识点:听不少职场前辈说,对于应届毕业生,面试时只要能说到核心重要的点,围绕这个点说一些自己的看法,面 ...
- 基于java平台的常用资源整理
这里整理了基于java平台的常用资源 翻译 from :akullpp | awesome-java 大家一起学习,共同进步. 如果大家觉得有用,就mark一下,赞一下,或评论一下,让更多的人知道.t ...
- 这里整理了基于java平台的常用资源
这里整理了基于java平台的常用资源 翻译 from :akullpp | awesome-java 大家一起学习,共同进步. 如果大家觉得有用,就mark一下,赞一下,或评论一下,让更多的人知道.t ...
- java中基本类型封装对象所占内存的大小(转)
这是一个程序,java中没有现成的sizeof的实现,原因主要是java中的基本数据类型的大小都是固定的,所以看上去没有必要用sizeof这个关键字. 实现的想法是这样的:java.lang.Runt ...
- java平台的常用资源
分离领域 翻译 from :akullpp | awesome-java 大家一起学习,共同进步. 如果大家觉得有用,就mark一下,赞一下,或评论一下,让更多的人知道.thanks. 构建 这里搜集 ...
- java中最常用jar包的用途说明
java中最常用jar包的用途说明,适合初学者 jar包 用途 axis.jar SOAP引擎包 commons-discovery-0.2.jar 用来发现.查找和实现可插入式接口,提供一些一般类实 ...
- Java中最常用的集合类框架之 HashMap
一.HashMap的概述 HashMap可以说是Java中最常用的集合类框架之一,是Java语言中非常典型的数据结构. HashMap是基于哈希表的Map接口实现的,此实现提供所有可选的映射 ...
随机推荐
- 三维凸包求重心到面的最短距离(HDU4273)
http://acm.hdu.edu.cn/showproblem.php?pid=4273 Rescue Time Limit: 2000/1000 MS (Java/Others) Memo ...
- (转)梯度下降法及其Python实现
梯度下降法(gradient descent),又名最速下降法(steepest descent)是求解无约束最优化问题最常用的方法,它是一种迭代方法,每一步主要的操作是求解目标函数的梯度向量,将当前 ...
- nginx集群配置
一.nginx集群目标 以nginx作为代理服务器,分别在两台部署web站点的机器上面轮询访问. 3台机器IP地址分别为: 1)192.168.189.133 (nginx代理服务器) 2)192 ...
- yii2框架dropDownList的下拉菜单用法介绍
Yii2.0 默认的 dropdownlist 的使用方法. 代码如下 复制代码 <?php echo $form->field($model, 'name[]')->dropDo ...
- MVC学习之HtmlHelper
1.为什么要使用HtmlHelper? 1.首先HtmlHelper是一个类型,MVC中的ViewPage<TModel>中的一个属性Html属性,这个属性的类型就是HtmlHelper& ...
- 如何在不改SQL的情况下优化数据库
主题简介 在数据库运维中我们会遇到各种各样的问题,这些问题的根源可能很明显,也可能被某种表象掩盖而使我们认不清.所以运维面临的两大问题就是,第一我们没有看清本质,第二应用不允许修改.那么我们如何解决这 ...
- WebSocket client for python
Project description websocket-client module is WebSocket client for python. This provide the low lev ...
- talib 中文文档(九):Volume Indicators 成交量指标
Volume Indicators 成交量指标 AD - Chaikin A/D Line 量价指标 函数名:AD 名称:Chaikin A/D Line 累积/派发线(Accumulation/Di ...
- Maven的pom文件配置
pom.xml文件如下: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http:// ...
- centos tomcat/resin安装配置 卸载系统自带的java tomcat安装配置 安装JDK resin安装配置 第二十八节课
centos tomcat/resin安装配置 卸载系统自带的java tomcat安装配置 安装JDK resin安装配置 第二十八节课 tomcat和java都不需要编译 tom ...