方法一:
/**
* 将指定的文件按着给定的文件的字节数进行分割文件
*
* @param filepath 源文件的路径
* @param fileSize 指定的小文件的大小[MB] 0:默认等分4份
*/
public static ArrayList<File> divide(String filepath, int fileSize) {
ArrayList<File> fileArrayList = new ArrayList<>();
if (!isExist(filepath)) {
ToastUtils.showToast("指定文件不存在");
} else {
FileInputStream in = null;
try {
File file = new File(filepath);
long fileLength = getFileSize(file);
long size = fileSize * 1024 * 1024;// MB-->byte
if (size <= 0) {
size = fileLength / 4;
}
byte[] bytes = new byte[(int) size];
// 取得被分割后的小文件的数目
int num = (fileLength % size != 0) ? (int) (fileLength / size + 1) : (int) (fileLength / size);
//输入文件流,即被分割的文件
in = new FileInputStream(file);
// 根据要分割的数目输出文件
for (int i = 0; i < num; i++) {
File outFile;
try {
//fixme 特殊分割字符需要添加\\
String[] split = file.getName().split("\\.");
if (split.length == 2) {
outFile = new File(downpath, split[0] + "_" + i + ".part");
} else {
throw new Exception("");
}
} catch (Exception e) {
outFile = new File(downpath, file.getName() + "_" + i + ".part");
}
if (outFile.exists()) {
outFile.delete();
}
outFile.createNewFile();
// 构建小文件的输出流
FileOutputStream out = new FileOutputStream(outFile);
out.write(bytes, 0, in.read(bytes));
out.flush();
out.close();
fileArrayList.add(new File(outFile.getAbsolutePath()));
}
} catch (Exception e) {
Log_Ma.Companion.e("Error[divide]:", e.toString());
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return fileArrayList;
}
方法二:
/**
* @param filepath 源文件的路径
* @param destDir 目标文件夹
* @param fileSize 拆分大小【单位MB】
* @throws Exception
*/
public static ArrayList<File> split(String filepath, String destDir, int fileSize) {
ArrayList<File> list = new ArrayList<>();
RandomAccessFile rand = null;
try {
// 创建文件对象
File src = new File(filepath);
File destFolder = new File(destDir);
if (!destFolder.exists()) {
destFolder.mkdirs();
}
rand = new RandomAccessFile(src, "r");// 输入流
// 计算拆分后文件的: 个数
double size = fileSize * 1024 * 1024;// MB-->byte
int count = (int) Math.ceil(src.length() / size);
byte[] buf = new byte[(int) size];
int len = 0;
for (int i = 1; i <= count; i++) {
// 定义拆分后的文件
File destFile;
try {
//fixme 特殊分割字符需要添加\\
String[] split = src.getName().split("\\.");
destFile = new File(destDir, split[0] + "_" + i + "." + split[1]);
} catch (Exception e) {
destFile = new File(destDir, src.getName() + "_" + i + ".mp4");
}
destFile.createNewFile();// 创建空的目标文件
RandomAccessFile dest = new RandomAccessFile(destFile, "rw");// 输出流
// 拷贝文件
len = rand.read(buf);
dest.write(buf, 0, len);
dest.close();
list.add(destFile);
}
return list;
} catch (Exception e) {
Log_Ma.Companion.e("Error[split]:", e.toString());
// 关闭资源
if (rand != null) {
try {
rand.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return list;
}
}
这是我的FileUtils工具类地址,有需要的可以下载使用