一:
题目:
写一个方法,将feige.exe文件分割为每份1MB大小的若干份(最后一份可以不满1MB),
存储在一个temp的文件夹中(每份文件名自己定义,例如1.temp 2.temp),
然后再写一个方法,将temp文件夹中的若干份合并为一个文件fg.exe
代码:
main
package com.ffyc.javaIO.zy.zy1;
import java.io.*;
public class T3 {
public static void main(String[] args) throws IOException {
File file1 = new File("D:/feige.exe");
resolve(file1);
compound(file1);
}
}
分割
public static void resolve(File file) throws IOException {
FileInputStream in = new FileInputStream(file);
BufferedInputStream bin = new BufferedInputStream(in);
File f = new File("D:/temp");
if(!f.exists()){
f.mkdir();
}
int size = 0;
byte[] bytes = new byte[1024*1024];
int i = 0;
while ((size = bin.read(bytes)) != -1){
i++;
FileOutputStream out = new FileOutputStream("D:/temp/"+i+".temp");
BufferedOutputStream bout = new BufferedOutputStream(out);
bout.write(bytes, 0, size);
bout.flush();
bout.close();
}
bin.close();
}
合并
public static void compound(File file) throws IOException {
FileOutputStream out = new FileOutputStream("D:/fg.exe");
File f = new File("D:/temp");
int num = f.list().length;
for (int i = 1; i <= num; i++) {
FileInputStream in = new FileInputStream("D:/temp/"+i+".temp");
byte[] bytes = new byte[1024];
int size = 0;
while ((size = in.read(bytes)) != -1) {
out.write(bytes, 0, size);
}
in.close();
}
out.close();
}
运行
二:
题目:
完善文件分割,将1MB文件分多次读写
思路:
文件的大小 file.length 总共的字节数
每份的大小 1MB
总共有多少份 = 总共的字节数/每份大小+1
fori 知道输入多少个文件了
FileOutputStream out = new FileOutputStream("D:/temp/"+i+".temp");
int size = 0;
byte[] bytes = new byte[1024];
int i = 0;
while ( )
代码:
package com.ffyc.javaIO.zy.zy2;
import java.io.*;
public class T3 {
public static void main(String[] args) throws IOException {
File f = new File("D:/temp");
if(!f.exists()){
f.mkdir();
}
File file = new File("D:/feige.exe");
FileInputStream in = new FileInputStream(file);
//文件长度 字节数量
long len = (file.length()%1024%1024)==0?(file.length()/1024/1024):(file.length()/1024/1024)+1;
for (int i = 0; i < len; i++) {
int sum = 0;
int size = 0;
byte[] bytes = new byte[1024];
FileOutputStream out = new FileOutputStream("D:/temp/"+i+".temp");
while ((size = in.read(bytes)) != -1){
sum+=size;
out.write(bytes,0,size);
//记录有没有1mb
if(sum>1024*1024){
break;
}
}
out.close();
}
in.close();
}
}
运行