public class Demo_02 {
/*
写一个方法,将feige.exe文件分割为每份1MB大小的若干份,
存储在一个temp的文件夹中(每份文件名自己定义),
1.temp 2.temp...然后再写一个方法,将这若干份合并为一个文件.
(注意路径,没有的文件要创建or自行补充代码)
*/
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("D:\\练习\\feige.exe");
String path = "D:\\练习\\temp";
//这里最好先获取源文件大小,然后按照想要的大小判断分成几份,再进行读写
byte[] bytes = new byte[1024*1024];
int len = -1;
int name = 0;
while ((len = fis.read(bytes)) != -1){ //读取字节数组大小的数据,没有数据返回-1
//将数据写入到指定文件中,没有文件会自动创建,有会刷新
FileOutputStream fos = new FileOutputStream(new File(path,++name+".temp.txt"));
//写入指定长度数据、有效数据
fos.write(bytes,0,len);
//流只能用一次,每次都要创建关闭
fos.close();
}
fis.close();
File file = new File(path);
//合并文件
mergeFile(file);
}
//也可以将分割代码封装起来,自行尝试
public static void mergeFile(File file) throws IOException {
File[] files = file.listFiles();//获取当前文件夹的所有子文件集合
FileOutputStream fos = new FileOutputStream("D:\\练习\\test\\feige1.exe");
byte[] bytes = new byte[8192];
int len;
for (File f:files){//每个文件数据写入到一个文件中
FileInputStream fis = new FileInputStream(f);//每次创建新的流
while ((len = fis.read(bytes)) != -1){
fos.write(bytes,0,len);
}
fis.close();
}
fos.close();
}
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交