Skip to content

[Bug] xlsx stream write leaves temp file #1137

Description

@nkuprins

Search before asking

  • I searched in the issues and found nothing similar.

Fesod version

main

JDK version

any

Operating system

Linux

Steps To Reproduce

When an xlsx is written to an OutputStream with .password(...), WriteContextImpl#doOutputStreamEncrypt07() first writes the workbook unencrypted to a temp file, then encrypts that file into the caller's stream (code). The temp file is deleted on every path except one:

FileOutputStream tempFileOutputStream = new FileOutputStream(tempXlsx);
try {
    writeWorkbookHolder.getWorkbook().write(tempFileOutputStream);   // 1. fails, e.g. disk full
} finally {
    try {
        writeWorkbookHolder.getWorkbook().close();
        tempFileOutputStream.close();                                 // 2. succeeds
    } catch (Exception e) {
        if (!tempXlsx.delete()) { ... }                               // only runs if 2. fails
        throw e;
    }
}
try (POIFSFileSystem fileSystem = openFileSystemAndEncrypt(tempXlsx)) {
    fileSystem.writeFilesystem(writeWorkbookHolder.getOutputStream());
} finally {
    if (!tempXlsx.delete()) { ... }                                   // never reached after 1.
}

If writing the temp file fails but closing succeeds, the exception from step 1 leaves the method without ever reaching a delete.

Current Behavior

The partly or fully written, unencrypted xlsx stays in Fesod's temp directory.

Expected Behavior

The temp file is deleted however doOutputStreamEncrypt07() exits, including when writing it fails.

Anything else?

Proposed fix. Move the delete into one outer finally that covers both the temp-file write and the encryption step:

FileOutputStream tempFileOutputStream = new FileOutputStream(tempXlsx);
try {
    try {
        writeWorkbookHolder.getWorkbook().write(tempFileOutputStream);
    } finally {
        writeWorkbookHolder.getWorkbook().close();
        tempFileOutputStream.close();
    }
    try (POIFSFileSystem fileSystem = openFileSystemAndEncrypt(tempXlsx)) {
        fileSystem.writeFilesystem(writeWorkbookHolder.getOutputStream());
    }
} finally {
    if (!tempXlsx.delete()) {
        throw new ExcelGenerateException("Can not delete temp File!");
    }
}
  • A successful write, a failed close and a failed encryption behave as before: the temp file is deleted in each case.
  • A failed write now deletes the temp file too.

Are you willing to submit a PR?

  • I'm willing to submit a PR!

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions