簡體   English   中英

使用 FileOutputStream 寫入后無法刪除文件

[英]Cannot delete file after writing using FileOutputStream

我有 RESTful Web 服務,它具有上傳文件的功能。 它運行良好,但我的問題是當我嘗試在 Windows 中手動刪除上傳的文件時,它說該文件已被使用。

要刪除這些文件,我需要停止 Glassfish 服務器。 我擔心的是內存使用情況,當用戶不斷上傳許多大文件時,這個未管理的代碼可能會導致一些問題。 我已經關閉了InputStreamFileOutputStream變量。 請看下面的代碼我不知道我錯過了什么。

@POST
@Path("upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public String upload(@FormDataParam("file") InputStream uploadedInputStream, 
        @FormDataParam("file") FormDataContentDisposition fileDetail, @Context HttpServletRequest request) {
    String json = "";
    FileOutputStream out = null;
    try {
        File dir = new File(new File(".").getCanonicalPath() + File.separatorChar + "incidentreport" + File.separatorChar + "uploaded" + File.separatorChar + deviceId);
        dir.mkdirs();
        String location = dir.getAbsolutePath() + File.separatorChar + fileDetail.getFileName();
        out = new FileOutputStream(new File(location));
        int read = 0;
        byte[] bytes = new byte[1024];
        out = new FileOutputStream(new File(location));
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }

        com.incidentreport.model.File file = new com.incidentreport.model.File(fileDetail.getFileName(), false);
        //FLAG FILE AS UPLOADED
        Response response = file.uploaded(deviceId, device.getId(), Util.toSqlTimestamp(dateUtc, "yyyy-MM-dd HH:mm:ss"));
        //DELETE UPLADED FILE IF FLAGGING NOT SUCCEED
        if(response.getStatus() != Response.SUCCESS) new File(location).delete();
        json = new Gson().toJson(response);
    } catch (Exception ex) {
        Logger.getLogger(FileResource.class.getName()).log(Level.SEVERE, null, ex);
        json = new Gson().toJson(new Response(Response.ERROR, ex.getMessage()));
    } finally {
        try {
            uploadedInputStream.close();
            uploadedInputStream = null;
            out.flush();
            out.close();
            out = null;
        } catch (IOException ex) {
            Logger.getLogger(FileResource.class.getName()).log(Level.SEVERE, null, ex);
            json = new Gson().toJson(new Response(Response.WARNING, ex.getMessage()));
        }
    }
    return json;
}

您已經將FileOutputStream out初始化FileOutputStream out兩次:一旦第二次賦值發生,第一個創建的流就會作為非引用對象保留在內存中,直到發生垃圾回收。 由於服務器沒有停止並且可能內存負載不是太高並且垃圾收集器不會收集垃圾,這就是您無法從 Windows 中刪除它的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM