package demo.io;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Properties;
class 切割文件 {
private static final int SIZE = 1048576;//1M大小
public static void main(String[] args) {
File file = new File("C:\\Users\\10340\\Desktop\\《Java基础入门》_课后习题.pdf");//源文件
File dir = new File("切割后文件目录");//切割后文件目录
//切割文件并指定存放碎片目录,单个文件大小(单位:M)
splitFile(file, dir, 1);
//合并 指定目录下碎片文件 到 指定目录
File destDir = new File("合并后文件目录");
mergeFile(dir, destDir);
}
//合并指定目录下碎片文件
private static void mergeFile(File dir, File destDir) {
if (!destDir.exists()) {//如果合并后文件目录不存在就创建
destDir.mkdirs();
}
ArrayList<FileInputStream> fileArr = new ArrayList<>();
File[] files = dir.listFiles();
for (File file : files) {
try {
if (!"part.txt".equals(file.getName())) {//part.txt中保存该文件名信息(无需添加)
fileArr.add(new FileInputStream(file));//将指定目录下碎片文件添加到ArrayList中
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//将ArrayList中每个碎片文件流用枚举返回出来
Enumeration<FileInputStream> en = Collections.enumeration(fileArr);
//根据枚举建立序列流
SequenceInputStream sis = new SequenceInputStream(en);
PrintStream ps = null;
FileInputStream fis = null;
int len = 0;
byte[] buf = new byte[1024];
try {
//获取被切割文件名
Properties prop = new Properties();
fis = new FileInputStream(new File(dir, "part.txt"));
prop.load(fis);
String fileName = prop.getProperty("fileName");//根据key获取文件名
ps = new PrintStream(new FileOutputStream(new File(destDir, fileName)));//将碎片文件合并至fileName文件
while ((len = sis.read(buf)) != -1) {
ps.write(buf, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
sis.close();
if (ps != null) {
ps.close();
}
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//切割文件并指定存放碎片目录
private static void splitFile(File file, File dir, int size) {
if (size < 0) {
System.out.println("size为非负数");
return;
}
System.out.println("源文件大小:" + (double) file.length() / SIZE + "M");
int partNum = (int) Math.ceil((double) file.length() / SIZE);//切割后生成的文件数量
System.out.println("切割后将生成文件数量:" + partNum);
if (partNum <= 1) {//如果切割后数量为1或者错误,就退出
System.out.println("切割生成文件数量错误");
return;
}
if (!dir.exists()) {
dir.mkdirs();//如果切割后文件目录不存在,就创建
}
FileInputStream fis = null;//源文件流
try {
fis = new FileInputStream(file);
int len = 0;
byte[] buf = new byte[SIZE];//一次读取1M大小的文件
int count = 0;
while ((len = fis.read(buf)) != -1) {//每次只读取1M大小数据
//按编号生成目的目录下的.part文件
FileOutputStream fos = new FileOutputStream(new File(dir, file.getName() + (++count)));
fos.write(buf, 0, len);
fos.close();
}
Properties prop = new Properties();
prop.setProperty("fileName", file.getName());//将要切割的文件名保存下来
PrintStream ps = new PrintStream(new FileOutputStream(new File(dir, "part.txt")));
prop.store(ps, "splitFileName");//注释:被切割文件名
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
切割合并文件
最新推荐文章于 2023-08-28 09:42:49 发布
1274

被折叠的 条评论
为什么被折叠?



