簡體   English   中英

使用 apache Apache Commons VFS 合並兩個文件的有效方法

[英]Efficient way to merge two files using apache 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 ");
            }
            }

文件非常大,我限制了 memory。有什么有效的方法可以更快地合並文件,而不是將整個內容作為字符串獲取? 使用任何第三方庫(如apache-commons-io而不是BufferedWriter )是否可以提高性能?

是的,正確的方法寫在FileContent文檔頁面的頂部:

要從文件中讀取,請使用 getInputStream() 返回的 InputStream。

因此,將您擁有的替換為:

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

請注意,您的代碼當前並未合並文件,而是用每個新文件覆蓋 file3.txt。 您可能應該 append 到 output stream 而不是覆蓋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM