我们需要将一个文件分割为每份1MB大小的若干份,存储在一个temp的文件夹中,然后再写一个方法,将这若干份合并为一个文件。
1、首先是将一个文件分割程若干个存储在temp文件夹中,为方便之后合并可以将temp中的文件按先后写入的顺序编号。
2、将文件合并到目标文件夹,你需要知道目标文件夹路径,你还需要从要输入的路径中取得复制后的文件名,从temp中读出分割的文件写入目标文件夹的目标文件中,后缀就可以。
3、注意:所有分割和合并的过程用户不可见,用户只需要输入要复制的文件路径,和目标文件夹路径即可
上代码:
import java.io.*;
import java.util.Scanner;
/*写一个方法,将一个文件分割为每份1MB大小的若干份,存储在一个temp的文件夹中,
然后再写一个方法,将这若干份合并为一个文件.*/
public class Test3 {
static File files = new File("G:\\temp");
/*这是一个程序入口*/
public static void main(String[] args) throws IOException {
Scanner data = new Scanner(System.in);
System.out.println("请输入你要复制的文件路径:");
String name = data.next();
System.out.println("请输入目标文件夹的路径");
String toFile = data.next();
Test3 test = new Test3();
test.cut(name);
test.merge(toFile,name);
}
/**
* 分割文件将其存入temp文件夹
* @param name 要复制的文件
*/
public void cut(String name) throws IOException {
String namefile = name.substring(name.lastIndexOf("."));
FileInputStream inputStream =null;
FileOutputStream outputStream = null;
try {
inputStream = new FileInputStream(name);
int i = 0;
int length = 0;
byte [] bytes = new byte[1048576];
while ((length = inputStream.read(bytes)) != -1) {
outputStream = new FileOutputStream(files+"\\"+i+namefile);
outputStream.write(bytes, 0, length);
outputStream.close();
System.out.println("第" + i + "个文件存储成功!");
i++;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
inputStream.close();
outputStream.close();
}
}
/**
* 将temp中的小文件合并成文一个大文件
* @param file 目标文件夹
* @param namecut 要复制的文件名,目的是获取其文件名
* @throws IOException 抛异常
*/
public void merge(String file, String namecut) throws IOException {
//获取temp文件夹个数
File[] files1 = files.listFiles();
String name = namecut.substring(namecut.lastIndexOf("\\"));
int i = 0;
for (File f : files1) {
FileInputStream inputStream = new FileInputStream(f);
FileOutputStream outputStream = new FileOutputStream(file + "\\"+name, true);
int length =0 ;
byte [] bytes = new byte[1048576];
while ((length = inputStream.read(bytes)) != -1) {
outputStream.write(bytes,0,length);
outputStream.close();
System.out.println("第"+i+"个文件存储成功");
i++;
}
inputStream.close();
}
//复制完毕后删除temp文件夹的文件
for (int j = 0; j < files1.length; j++) {
files1[j].delete();
}
}
}