java - 如果要编码 100k 个文档,PDF 文件编码到 base64 需要更多时间
问题描述
我正在尝试将 pdf 文档编码为 base64,如果它的数量较少(如 2000 个文档),它工作得很好。但是我有100k
额外的文件要编码。
对所有这些文件进行编码需要更多时间。有没有更好的方法来编码大数据集。?
请找到我目前的方法
String filepath=doc.getPath().concat(doc.getFilename());
file = new File(filepath);
if(file.exists() && !file.isDirectory()) {
try {
FileInputStream fileInputStreamReader = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
fileInputStreamReader.read(bytes);
encodedfile = new String(Base64.getEncoder().encodeToString(bytes));
fileInputStreamReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
解决方案
尝试这个:
弄清楚你需要编码多少个文件。
int files = Files.list(Paths.get(directory)).count();
将它们拆分成线程可以在 java 中处理的合理数量。IE)如果你有 100k 文件要编码。将其拆分为 1000 个 1000 个列表,类似这样。
int currentIndex = 0; for (File file : filesInDir) { if (fileMap.get(currentIndex).size() >= cap) currentIndex++; fileMap.get(currentIndex).add(file); } /** Its going to take a little more effort than this, but its the idea im trying to show you*/
如果计算机资源可用,则依次执行每个工作线程。
for (Integer key : fileMap.keySet()) { new WorkerThread(fileMap.get(key)).start(); }
您可以通过以下方式检查当前可用资源:
public boolean areResourcesAvailable() {
return imNotThatNice();
}
/**
* Gets the resource utility instance
*
* @return the current instance of the resource utility
*/
private static OperatingSystemMXBean getInstance() {
if (ResourceUtil.instance == null) {
ResourceUtil.instance = ManagementFactory.getOperatingSystemMXBean();
}
return ResourceUtil.instance;
}