我编写了一小段代码来使用 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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号