J'ai écrit un petit morceau de code pour effectuer du cryptage de pdf avec openpdf, et le sonarlint d'Intellij se plaignait de "Les ressources devraient être fermées" plus de détails ici
exemple de code Java ci-dessous
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()); } } }
juste un rappel, nous pouvons définir plusieurs ressources dans le bloc try
try ( FileOutputStream out = new FileOutputStream(new File("1_protected.pdf")); PdfReader reader = new PdfReader(new File("1.pdf").getPath()) )
trouvez un exemple de travail complet ici
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!