文件太大了,怎么办?
在开发进程中,众人往往会因文件传输问题而倍感困扰。文件体积过大,占用带宽尚属小事,更棘手的是传输中途突然中断,而后又得重新开始。不过,断点续传算是解决此难题的途径之一。此外,还有一法,即将一个大型文件拆分为多个种子,待全部传送完毕,再进行组装。下面,我以 Java 语言为例加以说明。
1、拆分文件代码
import java.io.*;
public class FileSplitter {
public static void main(String[] args) {
String sourceFilePath = "E:other/数字化转型建设方案.zip";
// 分割文件的大小,这里设为10MB,可以根据你的情况修改。
long chunkSize = 10 * 1024 * 1024;
splitFile(sourceFilePath, chunkSize);
}
private static void splitFile(String sourceFilePath, long chunkSize) {
File sourceFile = new File(sourceFilePath);
if (!sourceFile.exists() || !sourceFile.isFile()) {
return;
}
try (BufferedInputStream bis = new BufferedInputStream(new rceFile.getName().substring(sourceFile.getName().lastIndexOf('.') + 1);
while ((bytesRead = bis.read(buffer)) != -1) {
File partFile = new File(sourceFile.getParent(), fileNameWithoutExt +
bos.write(buffer, 0, bytesRead);
bytesWritten += bytesRead;
if (chunkSize != -1 && bytesWritten >= chunkSize) break;
bytesRead = bis.read(buffer);
}
}
index++;
}
System.out.println("文件分割完成,共生成了" + index + "个文件");
} catch (IOException e) {
e.printStackTrace();
}
}
}
2、组装文件代码
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FileAssembler {
public static void main(String[] args) {
// 分割后文件所在的目录路径
String sourceDirectoryName = "E:other/file";
// 目标文件路径,注意,这里是文件名
String targetFile = "d:/file/text.rar";
assembleFiles(sourceDirectoryName, targetFile);
}
private static void assembleFiles(String sourceDirPath, String targetFile) {
Path directoryPath = Paths.get(sourceDirPath);
if (!Files.isDirectory(directoryPath)) {
return;
}
try (BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(Paths.get(targetFile)))) {
// 获取所有部分文件,请注意,所有名称顺序要按生成的命名方式,不能修改
Stream<Path> paths = Files.list(directoryPath)
.filter(Files::isRegularFile)
.sorted();
for (Path partFile : paths.collect(Collectors.toList())) {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(partFile.toFile()))) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
}
}
System.out.println("文件组装已完成。请到目标路径下查看。");
} catch (IOException e) {
e.printStackTrace();
}
}
}

1万+

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



