Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple file delete code is not working in Java [duplicate]

Here is my code of deleting the pdf file

try {
    File file = new File(docObjectId + ".pdf");
    file.setWritable(true);
    System.out.println(file.length());
    if (file.delete()) {
        System.out.println(file.getName() + " is deleted!");
    } else {
        System.out.println("Delete operation is failed.");
    }
} catch (Exception e) {
    e.printStackTrace();
}

It goes to the else part of the code.

PDF file is in project root folder and I am able to delete it manually. Scratching my head now.

Here is complete method. It might be due to some other reason

public Response getContractDocument(@PathParam("docid") String docObjectId) throws Exception {
    DocumentumService documentumService = new DocumentumService(documentumConfigUtil);
    DocumentumDocumentBean docDocumentBean = documentumService.getContractDocContent(docObjectId, true);

    FileInputStream fileInputStream;
    fileInputStream = new FileInputStream(docDocumentBean.getDocFile());
    compressPdf(fileInputStream,docObjectId + ".pdf");

    fileInputStream = new FileInputStream(docObjectId + ".pdf");


    ResponseBuilder responseBuilder = Response.ok((Object) fileInputStream);
    try {
        File file = new File(docObjectId + ".pdf");
        System.out.println(file.getAbsolutePath());
        file.setWritable(true);
        System.out.println(file.length());

        File d = new File(file.getAbsolutePath());
        if (d.delete()) {
            System.out.println(file.getName() + " is deleted!");
        } else {
            System.out.println("Delete operation is failed.");
        }
    } catch(Exception e) {
        e.printStackTrace();
    }
    return responseBuilder.build();
}
like image 561
Adeel Avatar asked Dec 11 '25 07:12

Adeel


1 Answers

My experience is with windows. The reason that a file won't delete is always the same. Some object has a connection to the file and is holding it open. In this case, it looks like it might be fileInputStream.

Try this before you attempt to delete:

fileInputStream.close();
like image 116
Charles Knell Avatar answered Dec 13 '25 21:12

Charles Knell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!