try中如何使用资源文件和内存
收藏
从现在开始,我们要努力学习啦!今天我给大家带来《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());
}
}
}
合规
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中如何使用资源文件和内存》,希望本文对你有所帮助!关注米云公众号,给大家分享更多文章知识!
版本声明 本文转载于:dev.to 如有侵犯,请联系删除
