使用apache Commons VFS合并两个文件的有效方法



我有两个巨大的文件,需要合并到另一个文件中。目前我正在使用Apache Commons VFS连接到sftp服务器并合并它们。我正在使用以下逻辑合并文件

for(String file: filesToMerge){
try(             FileObject fileObject= utility.getFileObject();
OutputStream fileOutputStream= fileObject.resolveFile(pathToExport+"file3.txt").getContent().getOutputStream(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "ISO-8859-1");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter)
) {

String content=  fileObject.resolveFile(pathToExport+file).getContent().getString("ISO-8859-1");
bufferedWriter.write(content);
log.info("process completed");
} catch (Exception e) {
log.error("Error while mergingfiles. The error is: " + e);
} finally {
log.info("closing FTP session ");
}
}

文件很大,我的内存有限。有没有什么有效的方法可以更快地合并文件,而不是将整个内容作为字符串?使用任何第三方库(如apache-commons-io而非BufferedWriter(是否可以提高性能?

是的,正确的方法写在FileContent文档页面的顶部:

要读取文件,请使用getInputStream((返回的InputStream。

所以用替换您所拥有的

fileObject.resolveFile(pathToExport+file).getContent()
.getInputStream()
.transferTo(fileOutputStream);

请注意,您的代码当前不是在合并文件,而是用每个新文件覆盖file3.txt。您可能应该追加到输出流,而不是覆盖。

最新更新