问题描述:

i want to split array of Files by size. I set a maximum size is 4MB.

If the total size <= max size, i add to new List.

Here my method :

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;

}

And here is my array :

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);

....

....

I invoke the method like this :

long maxAttachmentSize = 4194304; // in bytes

List<File> resultSplit = fileSplit(files, maxAttachmentSize);

The problem is it not return List as part. It just return all List. Not separated part by part.

How to handle that?

Thank you.

网友答案:

Assuming that no file is bigger than max size, you can do this

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;
}
相关阅读:
Top