Rumah >Java >javaTutorial >Cara menggunakan fail sumber dan memori dalam percubaan
Saya menulis sekeping kecil kod untuk melakukan penyulitan pdf dengan openpdf, dan sonarlint intellij mengadu tentang “Sumber harus ditutup” butiran lanjut di sini
contoh kod java di bawah
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()); } } }
sekadar peringatan kita boleh mentakrifkan berbilang sumber dalam try block
try ( FileOutputStream out = new FileOutputStream(new File("1_protected.pdf")); PdfReader reader = new PdfReader(new File("1.pdf").getPath()) )
cari contoh lengkap yang berfungsi di sini
Atas ialah kandungan terperinci Cara menggunakan fail sumber dan memori dalam percubaan. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!