gpt4 book ai didi

java - 如果超过最大限制,则拆分文件数组

转载 作者:行者123 更新时间:2023-12-01 12:23:45 26 4
gpt4 key购买 nike

我想按大小拆分文件数组。我设置的最大大小是4MB。如果总大小<=最大大小,我添加到新的列表

这是我的方法:

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 作为一部分。它只是返回所有列表。不逐部分分开。怎么处理?

谢谢。

最佳答案

假设没有文件大于最大大小,您可以执行此操作

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

关于java - 如果超过最大限制,则拆分文件数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26499917/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com