2017-08-17 74 views
1

工作這是我刪除PDF文件簡單的文件刪除代碼未在Java中

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(); 
} 

它轉到代碼的其他部分的代碼。

PDF文件位於項目根文件夾中,我可以手動刪除它。現在抓我的頭。

這裏是完整的方法。它可能對其他一些原因

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(); 
} 
+0

你沒有刪除該文件。你是如果聲明只是檢查'文件'是否被刪除。 – Jixone

+0

我頭腦中流行的第一件事是你確定你使用的文件路徑是正確的嗎?如果是親戚,我會檢查以確保它是你的想法。 –

+0

試試這個,if(file.exists()){file.delete(); } – Tehmina

回答

0

變化if(file.delete)是由於

try { 
    file.delete(); 
    System.out.println("file deleted"); 
} catch(IOException e) { 
    System.out.println("file not deleted"); 
} 

異常可能是不準確的。

0

首先,檢查文件是否存在,然後刪除它。

請使用下面的代碼。它的工作正常,刪除方法非常清晰。我希望這會有所幫助。

public static void main(String[] args) { 
    try{ 
     File file = new File("C:/Users/Tehmina Yaseen/Documents/NetBeansProjects/FileDeletion/src/filedeletion/Myfile.pdf"); 

     if (file.exists()) { 
      file.delete(); 
      System.out.println(file.getName() + " is deleted!"); 
     } else { 
      System.out.println("Delete operation is failed."); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

這裏是輸出:

Output of the above code

0

我的經驗是有窗戶。文件不會被刪除的原因總是相同的。某些對象與該文件有連接並將其保持打開狀態。在這種情況下,它看起來可能是fileInputStream。

試試這個試圖刪除前:

fileInputStream.close(); 
+0

是的,你是對的。我嘗試關閉它,但隨後我收到任何迴應。我認爲我迷失在指針和連接中。 – Adeel

+0

你的意思是說d.delete()的值既不是真也是假?你是什​​麼意思「迴應我什麼都沒有」? – Charles

+0

return responseBuilder.build();返回任何內容,但文件將成功刪除。 – Adeel