我编写了一小段代码来使用 openpdf 进行一些 pdf 加密,而 intellij 的 sonarlint 抱怨“资源应该关闭”更多详细信息请参见这里
下面的示例 Java 代码
public class PasswordProtectedPDF { private static final Logger logger = Logger.getLogger(PasswordProtectedPDF.class.getName()); static final String USER_PASSWORD = "111"; static final String OWNER_PASSWORD = "111"; public static void main(String[] args) { try { File f = new File("1_protected.pdf"); FileOutputStream out = new FileOutputStream(f); File pdfFile = new File("1.pdf"); PdfReader reader = new PdfReader(pdfFile.getPath()); PdfStamper stamper = new PdfStamper(reader, out); HashMap<String, String> info = new HashMap<>(); info.put("Producer", ""); reader.getInfo().forEach((key, value) -> { logger.info("Key: " + key + ", Value: " + value); }); stamper.setInfoDictionary(info); stamper.setEncryption(USER_PASSWORD.getBytes(), OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128); stamper.close(); logger.info("Password protected PDF created successfully."); } catch (IOException e) { logger.severe("Error creating password protected PDF: " + e.getMessage()); } } }
public class PasswordProtectedPDF { private static final Logger logger = Logger.getLogger(PasswordProtectedPDF.class.getName()); static final String USER_PASSWORD = "111"; static final String OWNER_PASSWORD = "111"; public static void main(String[] args) { try ( FileOutputStream out = new FileOutputStream(new File("1_protected.pdf")); PdfReader reader = new PdfReader(new File("1.pdf").getPath()) ) { PdfStamper stamper = new PdfStamper(reader, out); HashMap<String, String> info = new HashMap<>(); info.put("Producer", ""); reader.getInfo().forEach((key, value) -> { logger.info("Key: " + key + ", Value: " + value); }); stamper.setInfoDictionary(info); stamper.setEncryption(USER_PASSWORD.getBytes(), OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128); stamper.close(); logger.info("Password protected PDF created successfully."); } catch (IOException e) { logger.severe("Error creating password protected PDF: " + e.getMessage()); } } }
只是提醒我们可以在 try 块中定义多个资源
try ( FileOutputStream out = new FileOutputStream(new File("1_protected.pdf")); PdfReader reader = new PdfReader(new File("1.pdf").getPath()) )
在这里找到完整的工作示例
以上是try中如何使用资源文件和内存的详细内容。更多信息请关注PHP中文网其他相关文章!