package com.ri;
import java.io.*;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
public class FileChunkingAndMergingTest {
private static final int CHUNK_SIZE = 1024 * 1024;
public static void main(String[] args) throws IOException {
String sourceFilePath = "D:\\apache-tomcat-8.5.75.zip";
String tempDirectoryPath = "C:\\abc";
String targetFilePath = "C:\\abc\\merged-tomcat.zip";
List<String> chunkFiles = splitFile(sourceFilePath, tempDirectoryPath, CHUNK_SIZE);
mergeChunks(chunkFiles, targetFilePath);
System.out.println("File has been successfully split and merged.");
}
public static List<String> splitFile(String sourceFilePath, String tempDirectoryPath, int chunkSize) throws IOException {
File sourceFile = new File(sourceFilePath);
File tempDir = new File(tempDirectoryPath);
if (!tempDir.exists() && !tempDir.mkdirs()) {
throw new IOException("Failed to create temporary directory: " + tempDirectoryPath);
}
List<String> chunkFilePaths = new ArrayList<>();
try (FileInputStream fis = new FileInputStream(sourceFile);
FileChannel fileChannel = fis.getChannel()) {
long fileSize = fileChannel.size();
for (long position = 0; position < fileSize; position += chunkSize) {
long remainingFileSize = fileSize - position;
long chunkEnd = Math.min(position + chunkSize - 1, fileSize - 1);
String chunkFileName = "chunk-" + position + ".part";
File chunkFile = new File(tempDirectoryPath, chunkFileName);
try (FileOutputStream fos = new FileOutputStream(chunkFile);
FileChannel outChannel = fos.getChannel()) {
fileChannel.transferTo(position, Math.min(chunkSize, remainingFileSize), outChannel);
}
chunkFilePaths.add(chunkFile.getAbsolutePath());
}
}
return chunkFilePaths;
}
public static void mergeChunks(List<String> chunkFilePaths, String targetFilePath) throws IOException {
File targetFile = new File(targetFilePath);
try (FileOutputStream fos = new FileOutputStream(targetFile)) {
FileChannel outChannel = fos.getChannel();
for (String chunkFilePath : chunkFilePaths) {
File chunkFile = new File(chunkFilePath);
try (FileInputStream fis = new FileInputStream(chunkFile);
FileChannel inChannel = fis.getChannel()) {
inChannel.transferTo(0, inChannel.size(), outChannel);
}finally {
if (!chunkFile.delete()) {
System.err.println("Failed to delete the chunk file: " + chunkFilePath);
}
}
}
}
}
}