最近在研究串口数据的接收和发送,涉及到通过串口,将图片分包写入到本地的问题。代码如下:
@Test
public void pic() {
String path = "D:/atest/water.jpg"; //源原件
String path1 = "D:/atest/water1.jpg"; //目标文件
for(int i = 0;i<4; i++){
byte[] buff = randomRed(path, i);// 分段读取图片
if(null!=buff){
insert(path1, i, buff); //分段写入图片
}
}
}
/**
* 分包读取
*
* @parampath文件路径
* @parampointe指针位置
* **/
public static byte[] randomRed(String path, int pointe) {
try {
RandomAccessFile randomAccessFile = new RandomAccessFile(path, "r");
//获取RandomAccessFile对象文件指针的位置,初始位置是0
randomAccessFile.seek(pointe*1024*100);// 移动文件指针位置 和每次读取文件的大小有关
byte[] bytes = new byte[1024*100]; //每次读取文件的大小
int readSize = randomAccessFile.read(bytes);
if (readSize <= 0) {
randomAccessFile.close();
return null;
}
//不足1024需要拷贝去掉空字节
if (readSize < 1024 * 100) {
byte[] copy = new byte[readSize];
System.arraycopy(bytes, 0, copy, 0, readSize);
return copy;
}
randomAccessFile.close();
return bytes;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 分包写入
*
* @paramfileName文件名
* @parampoints指针位置
* @paraminsertContent插入内容
* **/
public static void insert(String fileName, long points, byte[] data) {
try {
File tmp = new File(fileName);
RandomAccessFile randomAccessFile = new RandomAccessFile(tmp, "rw");
randomAccessFile.seek(points*1024*100); //移动文件记录指针的位置,
randomAccessFile.write(data); //调用了seek(start)方法,是指把文件的记录指针定位到start字节的位置。也就是说程序将从start字节开始写数据
randomAccessFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
结果如下: