我編寫了一小段程式碼來使用 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中文網其他相關文章!