I want to delete the strings file1 and file2 after its merged to a single pdf merge12.
Please suggest your valuable ideas.. Thanks in advance

package com;

import java.io.FileOutputStream;
import java.util.ArrayList;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;

/*
 * author 
 * @282532
 */


public class PdfMerger {
public static void main(String args[]){
    String file1 = "d:\\PR00002.PDF";
    String file2 = "d:\\PR00003.PDF";
    String mergedFileLocation = "d:\\merge12.pdf";

    String filesTobeMerges[] = new String[] { file1, file2 }; 
    mergeMyFiles(filesTobeMerges, mergedFileLocation); 
}

public static void mergeMyFiles(String filesTobeMerged[],String mergedFileLocation){
    System.out.println("Starting to merge files...");
    System.out.println("total number of files to be merged"+filesTobeMerged.length +"\n");
    try{
        int pageOffset = 0;
        ArrayList masterBookMarkList = new ArrayList();

        String outFile = mergedFileLocation; 
        Document document = null; 
        PdfCopy writer = null; 
        PdfReader reader = null;  
        for (int fileIndex = 0; fileIndex< filesTobeMerged.length; fileIndex++) {
            reader = new PdfReader(filesTobeMerged[fileIndex]);
            System.out.println("Reading file" +filesTobeMerged[fileIndex]);

            /** * Replace all the local named links with the actual destinations.
             * *
             */
            reader.consolidateNamedDestinations(); 
            int totalPages = reader.getNumberOfPages(); 

            /** * Merging the files to the first file.
             *  * If we are passing file1, file2 and file3, 
             *  * we will merge file2 and file3 to file1.
             *   */
            if (fileIndex == 0) {
                /** * Create the document object from the reader */
                document = new Document(reader.getPageSizeWithRotation(1));

                /** * Create a pdf write that listens to this document.
                 *  * Any changes to this document will be written the file 
                 *  * * outFile is a location where the final merged document * will be written to. */

                System.out.println("Creating an empty PDF..."); 
                writer = new PdfCopy(document, new FileOutputStream(outFile)); 
                /** * Open this document */
                document.open();
            }

            /** * Add the conent of the file into this document (writer).
             *  * Loop through multiple Pages */
            System.out.println("Merging File: "+filesTobeMerged[fileIndex]); 
            PdfImportedPage page; 
            for (int currentPage = 1; currentPage <= totalPages; currentPage++) { 
                page = writer.getImportedPage(reader, currentPage); 
                writer.addPage(page);
                }  
            }
        document.close(); 
        System.out.println("File has been merged and written to-"+mergedFileLocation); 

    }catch(Exception e){
        e.printStackTrace();
    }
}
}

Dani AI

Generated

Short summary and what to watch for: assigning file1 = "" or file1 = null only changes the Java variable — it does not remove the physical PDF. As pointed out, you must delete the filesystem entries. Also remember what and noted: the most common reason a delete call fails is that the file is still open (locked) by your own process. Close every PdfReader/stream before attempting deletion, and only delete after you have verified the merged file exists and looks valid.

Practical checklist

  • Finish the merge and close all resources (each PdfReader, the PdfCopy/writer and the Document).
  • Verify the merged PDF exists and has size > 0.
  • Delete originals with File.delete() or Files.deleteIfExists() and handle/report failures.
  • On Windows a file can fail to delete if it is still open by any process; explicitly call reader.close() (or use try-with-resources) to release handles. deleteOnExit() is a last-resort option (deletes at JVM shutdown).

Example deletion pattern to run after a successful merge:

// after merge finished and document/writer are closed
Path merged = Paths.get(mergedFileLocation);
if (Files.exists(merged) && Files.size(merged) > 0) {
    for (String p : filesTobeMerged) {
        try {
            boolean deleted = Files.deleteIfExists(Paths.get(p));
            System.out.println("Delete " + p + ": " + deleted);
        } catch (IOException ex) {
            System.err.println("Could not delete " + p + ": " + ex.getMessage());
            // log stacktrace or handle retry if needed
        }
    }
} else {
    System.err.println("Merged file missing or empty; originals not deleted.");
}

Troubleshooting tips: if deletion still fails, print Files.exists(...) and Files.isWritable(...), ensure no other thread/process opened the file, and make sure every PdfReader is closed inside the merge loop (call reader.close() in a finally block or use try-with-resources).

Recommended Answers

All 10 Replies

file1 = null;
file2 = null;
?

what exactly do you mean by 'delete the strings'?

you can simply assign null value to the variable string variable = ""; after the data has been merged.

do keep in mind though,
String a = "";
is not the same as:
String a = null;

Thanks for your reply.What I mean by delting is that I dont want these files in the folder after these files are merged to a single pdf merge12.


file1 = null;
file2 = null;
?

what exactly do you mean by 'delete the strings'?

this has nothing to do with the String objects.
you should check out the delete method of the File class.

Hi Thanks for your reply.I have tried by assigning string file1 ="";
But its not working.

you can simply assign null value to the variable string variable = ""; after the data has been merged.

Hi Thanks for your reply.I have tried by assigning string file1 ="";
But its not working.

that's because manipulating a String object has nothing to do with what you try to do.
read my last post.

but the problem is that am storing these file names in a string.R u telling me to change this and store it in a file

this has nothing to do with the String objects.
you should check out the delete method of the File class.

no, I'm saying whether and how you have a filename stored has nothing to do with whether there (still) is a physical file on your hard drive.

Thanks a lot.I got now what u meant.I was able to delete the files after merging. Thank You stultuske

no, I'm saying whether and how you have a filename stored has nothing to do with whether there (still) is a physical file on your hard drive.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.