这似乎是沉浸式的重复问题,但我反复检查并发布了解决方案。如果文件未在该限制内完成,我必须从5 MB限制的源文件目录中生成一个zip,必须生成另一个zip,依此类推。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class QDE_ZIP {
public static String createZIP() {
try {
String zipFileName = "abc";
String directoryPath = "/Users/Music";
final int BUFFER = 104857600; // 100MB
final long MAX_ZIP_SIZE = 5242880L; //5 MB
long currentSize = 0;
int zipSplitCount =0;
File folder = new File("/Users/source/");
List<String> files = new ArrayList<>();
//folder.listFiles().
for (File f : folder.listFiles()) {
if (f.isFile() && !f.isDirectory()) {
files.add(f.getAbsolutePath());
}
}
//String files[] = filesToZip.split(",");
if (!directoryPath.endsWith("/")) {
directoryPath = directoryPath + "/";
}
byte fileRAW[] = new byte[BUFFER];
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(directoryPath + zipFileName.toUpperCase()));
ZipEntry zipEntry;
FileInputStream entryFile;
System.out.println("files list size:"+files.size());
for (String aFile : files) {
System.out.println("files list aFile:"+aFile);
zipEntry = new ZipEntry(aFile);
if (currentSize >= MAX_ZIP_SIZE)
{
zipSplitCount ++;
//zipOut.closeEntry();
zipOut.close();
zipOut = new ZipOutputStream(new FileOutputStream(directoryPath + zipFileName.toLowerCase().replace(".zip", "_"+zipSplitCount+".zip").toUpperCase()));
currentSize = 0;
}
zipOut.putNextEntry(zipEntry);
entryFile = new FileInputStream(directoryPath + aFile);
int count;
while ((count = entryFile.read(fileRAW, 0, BUFFER)) != -1) {
zipOut.write(fileRAW, 0, count);
System.out.println("number of Bytes read = " + count);
}
entryFile.close();
zipOut.closeEntry();
currentSize += zipEntry.getCompressedSize();
}
zipOut.close();
System.out.println(directoryPath + " -" + zipFileName + " -Number of Files = " + files.size());
} catch (FileNotFoundException e) {
return "FileNotFoundException = " + e.getMessage();
} catch (IOException e) {
return "IOException = " + e.getMessage();
} catch (Exception e) {
return "Exception = " + e.getMessage();
}
return "1";}public static void main(String[] args) throws Exception {
System.out.println("started:");createZIP();}}
****and another code :
how to create java zip archives with a max file size limit
我在等一个更好的例子。您将接受您的代码和建议。