方法一:
/**
* 將指定的文件按着給定的文件的字節數進行分割文件
*
* @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工具類地址,有需要的可以下載使用