我想按大小拆分文件数组。我设置的最大大小是4MB。
如果总大小< =最大尺寸,我会添加到新的List
。
这是我的方法:
public List<File> fileSplit(File [] files, long maxAttachmentSize) {
int i = 0;
long totalAttachmentSize = 0;
List<File> list = new ArrayList<File>();
for (int j = 0; j < files.length; j++) {
File file = files[i];
totalAttachmentSize += file.length();
list.add(file);
if (totalAttachmentSize > maxAttachmentSize) {
//part += 1;
break;
}
}
return list;
}
这是我的阵列:
String [] attachments = {
"/Users/fanjavaid/Documents/data.json",
"/Users/fanjavaid/Documents/master.psd",
"/Users/fanjavaid/Pictures/ceria.jpg",
"/Users/fanjavaid/Desktop/All Data LM.dsv",
"/Users/fanjavaid/Desktop/LM August 01 - Now.xlsx",
"/Users/fanjavaid/Desktop/Email_GoGreen.png",
"/Users/fanjavaid/Desktop/Archive.zip",
"/Users/fanjavaid/Desktop/Email_Veri2144202172009.zip",
"/Users/fanjavaid/Desktop/Screenshot Collection.zip",
"/Users/fanjavaid/Desktop/logo-big.jpg",
"/Users/fanjavaid/Desktop/Mbak Putri.psd"
};
File [] files = convertToFile(attachments);
Arrays.sort(files, SizeFileComparator.SIZE_COMPARATOR);
.... ....
我调用这样的方法:
long maxAttachmentSize = 4194304; // in bytes
List<File> resultSplit = fileSplit(files, maxAttachmentSize);
问题是它不会将List作为部分返回。它只返回所有列表。没有逐个分开。 如何处理?
谢谢。
答案 0 :(得分:1)
假设没有文件大于最大尺寸,你可以这样做
public List<List<File>> fileSplit(File [] files, long maxAttachmentSize) {
long totalAttachmentSize = 0;
List<List<File>> allLists = new ArrayList<>();
List<File> currList = new ArrayList<File>();
allLists.add(currList);
for (File file : files) {
long fileSize = file.length();
if ((totalAttachmentSize + fileSize) <= maxAttachmentSize) {
currList.add(file);
totalAttachmentSize += fileSize;
} else {
totalAttachmentSize = fileSize;
currList = new ArrayList<File>();
allLists.add(currList);
currList.add(file); // assuming no file is bigger than maxAttachmentSize
}
}
return allLists;
}