写一个方法,将feige.exe文件分割为每份1MB大小的若干份,存储在一个temp的文件夹中(每份文件名自己定义,例如1.temp 2.temp), 然后再写一个方法,将这若干份合并为一个文件.
package com.ffyc.javaio.file;
import java.io.*;
public class HomeWork2{
public static void main(String[] args) {
File f1 = new File("D:\\非凡英才\\java1\\2022-7-11_java第八章IO\\练习\\feige.exe");
try {
cut(new File("D:\\非凡英才\\java1\\2022-7-11_java第八章IO\\练习\\feige.exe"), 1024 * 1024);
merge(new File("D:\\temp"));
} catch (FileNotFoundException e){
e.printStackTrace();
System.out.println("文件找不见");
}catch (IOException e) {
e.printStackTrace();
System.out.println("读写异常");
}
}
/*
分割
*/
public static void cut(File file,int n) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(file);
File f = new File("D:/temp");
if(!f.exists()){
f.mkdir();
}
int size =0;
byte []b = new byte[n];
int i = 1;
while((size = in.read(b))!=-1){
out = new FileOutputStream("D:/temp/"+ i++ +".temp");
out.write(b,0,size);
}
}finally {
if (in!=null) {
in.close();
}
if (out!= null){
out.close();
}
}
}
/*
合并
*/
public static void merge(File f) throws IOException {
String [] array = f.list();
FileOutputStream out = new FileOutputStream("D:/feige.exe");
for (int i = 0; i < array.length; i++) {
FileInputStream in = new FileInputStream("D:/temp/"+(i+1)+".temp");
byte[]b = new byte[1024];
int size = 0;
while((size = in.read(b))!=-1){
out.write(b,0,size);
}
in.close();
}
out.close();
}
}