try中如何使用资源文件和内存
我编写了一小段代码来使用 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()); } } } </string>
合规
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()); } } } </string>
只是提醒我们可以在 try 块中定义多个资源
try ( FileOutputStream out = new FileOutputStream(new File("1_protected.pdf")); PdfReader reader = new PdfReader(new File("1.pdf").getPath()) )
在这里找到完整的工作示例
以上就是try中如何使用资源文件和内存的详细内容,更多请关注www.sxiaw.com其它相关文章!