这里介绍的是将一个大的文件切割为若干个小的文件并存放在不同的目录下,文件目录要求足够多,且文件和目录不能重名。
文件切割的代码:
package cn.tedu.practice;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.UUID;
/**
* 文件切割放入不同的目录下,且目录不能同名,目录层级足够多,文件放入也不能重名
* @author 11092
*
*/
public class FileSplit {
public static void main(String[] args) {
//1,拿到需要切割的文件
File file = new File("D:\\day23-am.avi");
//2,拿到文件输入流
FileInputStream fis = null;
//3,创建一个properties文件来存放切割的文件的个数,以及每块对应的路径
Properties prop = new Properties();
//4,定义一个变量记录切割的文件个数
int count = 0;
try {
fis = new FileInputStream(file);
//字节数组 5M 大小 每次切割
byte[] buffer = new byte[1024*1024*5];
int len = -1;
while((len=fis.read(buffer))!=-1){
//生成随机的32位二进制数
int random = UUID.randomUUID().hashCode();
//再将随机的32位随机二进制数转为8位的16进制的字符串
String str = Integer.toHexString(random);
//不足8位补0
int rest = 8 - str.length();
for (int i=0;i<rest;i++) {
str += "0";
}
//定义文件存放的文件路径
String path = "D:\\split";
//生成8级目录
for (char c : str.toCharArray()) {
path += "\\" + c ;
}
//创建文件夹
new File(path).mkdirs();
//加上文件名
path += "\\"+UUID.randomUUID();
File destFile = new File(path);
//某块文件对应的路径都存放进配置文件中,便于合并
prop.setProperty(""+count, path);
count++;
//拿到输出流将切割的文件写入指定的文件夹下
FileOutputStream fos = new FileOutputStream(destFile);
fos.write(buffer, 0, len);
fos.close();
}
prop.setProperty("count", count+"");
prop.store(new FileOutputStream("day23-am.propertites"), null);
} catch (IOException e) {
e.printStackTrace();
}
}
}
文件合并的代码
package cn.tedu.practice;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.Properties;
import java.util.Vector;
/**
* 将文件合并
* @author 11092
*
*/
public class FileUnion {
public static void main(String[] args) {
Properties prop = new Properties();
FileOutputStream fos = null;
SequenceInputStream sis = null;
try {
prop.load(new FileInputStream("day23-am.propertites"));
int count = Integer.parseInt(prop.getProperty("count"));
Vector<InputStream> vector = new Vector<>();
for (int i = 0; i < count; i++) {
vector.addElement(new FileInputStream(new File(prop.getProperty(""+i))));
}
//拿到合并流
sis = new SequenceInputStream(vector.elements());
//将文件写入指定的目录下的文件中
fos = new FileOutputStream(new File("D:\\a.avi"));
byte[] buffer = new byte[1024*1024];
int len = -1;
while((len=sis.read(buffer))!=-1){
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}finally{
fos = null;
}
}
if(sis!=null){
try {
sis.close();
} catch (IOException e) {
e.printStackTrace();
}finally{
sis = null;
}
}
}
}
}