java 根据特定数据结构 打自定义包

组长分配了一个任务,按照特定的数据结果打一个 xxx.pkg的包,然后解压出来后不变~
刚刚开始觉得蛮难的,感觉无从下手,认真分析了20分钟,有思路了!
首先看特定的数据格式

public static void message(){
// String package_header_signature = "hello";

// int file_num=8;
//
// for(int i=0;i<8;i++){
// int file_path_length="";
int file_size ="";
// String file_path="";

// }
// 只列了简单几个,原因都懂的!

// }

大概就是这样子,其实信息再多思路一样也没问题!下面是打包的方法!!
思路是将所有的信息全部转化为二进制存储!


public static void test(String src,String target) throws Exception{
File file =new File(src);
//String target = "g://test.pkg";
File targetFile = new File(target);
if(!targetFile.exists()){
targetFile.createNewFile();
}
OutputStream os = new FileOutputStream(targetFile);

//write some message
String package_header_signature = "hello";

addByte(package_header_signature.getBytes(), os, 4);
//文件个数
int filesum=0;
//文件路径
List<String> strList = new ArrayList<String>();
filesum =listFlieSum(file,strList);

//加入文件个数
addByte(intToByte(filesum,1),os, 1);

for(int i=0;i<strList.size();i++){
File fileInfo = new File(strList.get(i));
String file_path = fileInfo.getAbsolutePath();
int file_path_length = file_path.length();
int file_size = getFileSize(fileInfo);
//加入文件路径长度
addByte(intToByte(file_path_length,1), os, 1);//文件路径的长度
//加入文件大小
addByte(intToByte(file_size,4), os, 4);//文件大小
//加入文件路径
addByte(file_path.getBytes(), os, file_path.length());//文件路径
}
listFile(file,os);

String crc32 = getFileCRCCode(targetFile);
byte[] crcbyte = crc32.getBytes();

os.close();


}


经常碰到的问题就是:bit byte byte[] int 之间的转化!
这里谢谢javaeye的一个网友。


/**
* int to byte[] 支持 1或者 4 个字节
* @param i
* @param len
* @return
*/
public static byte[] intToByte(int i,int len) {
byte[] abyte=null;
if(len==1){
abyte = new byte[len];
abyte[0] = (byte) (0xff & i);
}else{
abyte = new byte[len];
abyte[0] = (byte) (0xff & i);
abyte[1] = (byte) ((0xff00 & i) >> 8);
abyte[2] = (byte) ((0xff0000 & i) >> 16);
abyte[3] = (byte) ((0xff000000 & i) >> 24);
}
return abyte;
}
public static int bytesToInt(byte[] bytes) {
int addr=0;
if(bytes.length==1){
addr = bytes[0] & 0xFF;
}else{
addr = bytes[0] & 0xFF;
addr |= ((bytes[1] << 8) & 0xFF00);
addr |= ((bytes[2] << 16) & 0xFF0000);
addr |= ((bytes[3] << 24) & 0xFF000000);
}
return addr;
}


/**
* 读取byte []
* @param b
* @param target
* @throws Exception
*/
public static void addByte(byte[] b,OutputStream os, int len) throws Exception{
// File targetpkg = new File(target);
byte[] by = new byte[len];
if (b.length > len) {
os.write(b, 0, len);
} else {
int l = len - (b.length-1);

while (--l > 0) {
os.write(0);
}
os.write(b, 0, b.length);
}
}


ok! 打包基本基本没问题了,解包才是关键。请看下一篇!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值