Apache POI-加密大于2GB的XLSX文件失败

时间:2019-04-12 19:43:54

标签: java apache-poi

编辑:对于那些将此标记为重复的对象,这(直接)与数组限制无关。这与当前无法处理较大文件的Apache POI库有关。

我已经使用apache POI生成了大约6GB的XLSX文件。当我在Excel中打开文件时,该文件运行正常。我现在正在尝试在生成文件时添加加密,但是任何大于2GB的文件都会遇到错误(小于2GB的文件可以很好地加密并且也可以在Excel中打开)

org.apache.poi.util.RecordFormatException: Can't allocate an array > 2147483647
    at org.apache.poi.util.IOUtils.safelyAllocate(IOUtils.java:545)
    at org.apache.poi.poifs.nio.ByteArrayBackedDataSource.extend(ByteArrayBackedDataSource.java:85)
    at org.apache.poi.poifs.nio.ByteArrayBackedDataSource.write(ByteArrayBackedDataSource.java:62)
    at org.apache.poi.poifs.filesystem.POIFSFileSystem.createBlockIfNeeded(POIFSFileSystem.java:453)
    at org.apache.poi.poifs.filesystem.POIFSStream$StreamBlockByteBuffer.createBlockIfNeeded(POIFSStream.java:223)
    at org.apache.poi.poifs.filesystem.POIFSStream$StreamBlockByteBuffer.write(POIFSStream.java:245)
    at org.apache.poi.poifs.filesystem.DocumentOutputStream.write(DocumentOutputStream.java:144)
    at org.apache.poi.util.IOUtils.copy(IOUtils.java:402)
    at org.apache.poi.poifs.crypt.ChunkedCipherOutputStream$EncryptedPackageWriter.processPOIFSWriterEvent(ChunkedCipherOutputStream.java:299)
    at org.apache.poi.poifs.filesystem.POIFSDocument.<init>(POIFSDocument.java:117)
    at org.apache.poi.poifs.filesystem.DirectoryNode.createDocument(DirectoryNode.java:373)
    at org.apache.poi.poifs.crypt.ChunkedCipherOutputStream.close(ChunkedCipherOutputStream.java:250)
    .....

我用来加密文件的代码是:

    public static void encryptFile(File unencryptedFile, File outputFile, String password) throws IOException, InvalidFormatException, GeneralSecurityException
    {
        POIFSFileSystem fs = new POIFSFileSystem();
        EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);

        Encryptor enc = info.getEncryptor();
        enc.confirmPassword(password);

        try(OPCPackage opc = OPCPackage.open(unencryptedFile))
        {
            try(OutputStream os = enc.getDataStream(fs))
            {
                opc.save(os);
            } <-----EXCEPTION IS THROWN HERE BY THE CALL TO close()
        } 


        try(FileOutputStream fos = new FileOutputStream(outputFile))
        {
            fs.writeFilesystem(fos);
        }
    }

该try块退出时,close()引发异常(如上面的代码中所述)。有人知道我可以使用另一种方法来加密不限于2GB的文件吗?

0 个答案:

没有答案