java—使用ApachePOI为带有hadoop文件系统api的xlsx设置密码

fzsnzjdm  于 2021-05-26  发布在  Spark
关注(0)|答案(0)|浏览(256)

使用hadoop文件系统api和poi来设置xlsx文件的密码有什么解决方法吗?下面的代码在windows文件系统中工作,但是如何将其移植到hadoop文件系统api中呢?我尝试过将outputstream转换为hadoop流,但没有成功

public class EncryptTest {
    public static void main(String[] args) throws Exception {
        encryptHSSF();
        encryptXSSF();

        for (final String file : new String[] {"test.xls","test.xlsx"}) {
            try (Workbook wb = WorkbookFactory.create(new File(file), "pass")) {
                System.out.println(wb.getSheetAt(0).getRow(0).getCell(0).getStringCellValue());
            }
        }
    }

    public static void encryptHSSF() throws IOException, EncryptedDocumentException, InvalidFormatException {
        generateFile("test.xls");

        try (HSSFWorkbook hwb = (HSSFWorkbook)WorkbookFactory.create(new File("test.xls"))) {
            Biff8EncryptionKey.setCurrentUserPassword("pass");
            hwb.write();
        }
    }

    public static void encryptXSSF() throws IOException, GeneralSecurityException {
        generateFile("test.xlsx");

        try (POIFSFileSystem fs = new POIFSFileSystem()) {
            EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
            Encryptor enc = info.getEncryptor();
            enc.confirmPassword("pass");

            try (OutputStream os = enc.getDataStream(fs)) {
                try (InputStream is = new FileInputStream("test.xlsx")) {
                    IOUtils.copy(is, os);
                }
            }

            try (FileOutputStream fos = new FileOutputStream("test.xlsx")) {
                fs.writeFilesystem(fos);
            }
        }
    }

    public static void generateFile(final String filename) throws IOException {
        try (Workbook wb = filename.endsWith("x") ? new XSSFWorkbook() : new HSSFWorkbook()) {
            wb.createSheet("test").createRow(0).createCell(0).setCellValue("Test");
            try (FileOutputStream fos = new FileOutputStream(filename)) {
                wb.write(fos);
            }
        }
    }
}

共享编辑

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题