大数据 文件解档归档

1,把小文件归成一个大文件需要做的

    1,1 用一个字节存储小文件的文件名长,然后把名字字节存入,把文件能容长度 用int 类型转换为 4个字节存储长度,然后存储类型;

2,解档 就是按照这个上面的步骤的反步骤进行

// 把srcFile 文件夹下的文件都 归档到 desFile 中去
public static void mergeFile(File srcFile, File desFile) throws Exception {
File[] listF = srcFile.listFiles();
File fi = new File(desFile, "merge.dat");
FileOutputStream fos = new FileOutputStream(fi);
for (File file : listF) {
if (file.isFile()) {
String files = file.getName();
// 文件名数组 byte[] 数组
byte[] fileName = files.getBytes();
// 文件名字节长度
int fileLength = fileName.length;
// 文件内容长度 因为感觉文件长度 int 类型足够
int fileLeng = (int) file.length();
byte[] fl = int2Bytes(fileLeng);
fos.write(fileLength);
fos.write(fileName);
fos.write(fl);
copy(file, fos);
}
}
fos.close();
}


// 归档 copy文件方法
private static void copy(File file, FileOutputStream fos) throws Exception {
FileInputStream fis = new FileInputStream(file);
byte[] bt = new byte[1024];
int len = 0;
while ((len = fis.read(bt)) != -1) {
fos.write(bt, 0, len);
}
fis.close();
}


// 解档
public static void explainFile(File srcFile, File desFile) throws Exception {
FileInputStream fis = new FileInputStream(srcFile);
int len = 0;
while ((len = fis.read()) != -1) {
byte[] bt = new byte[len];
int read = fis.read(bt);
String fileName = new String(bt);
File newFile = new File(desFile, fileName);

byte[] length = new byte[4];
fis.read(length);
int bytes2Int = bytes2Int(length);
byte[] filedata = new byte[bytes2Int];
fis.read(filedata);
FileOutputStream fos = new FileOutputStream(newFile);
fos.write(filedata);
fos.close();
}
}


public static byte[] int2Bytes(int n) {
byte[] buf = new byte[4];
buf[0] = (byte) (n >> 24);
buf[1] = (byte) (n >> 16);
buf[2] = (byte) (n >> 8);
buf[3] = (byte) (n >> 0);
return buf;
}


public static int bytes2Int(byte[] bys) {
int i0 = (bys[0] & 0xFF) << 24;
int i1 = (bys[1] & 0xFF) << 16;
int i2 = (bys[2] & 0xFF) << 8;
int i3 = (bys[3] & 0xFF) << 0;
return i0 + i1 + i2 + i3;

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值