Can't delete file after it gets written

橙三吉。 提交于 2019-12-11 19:44:35

问题


I'll put my code first:

@Post
public Representation post(InputStream zip) throws Throwable {
    createFile(zip, "C:/temp");
    return new StringRepresentation("File uploaded");
}    

public void createFilee(InputStream zipStream, uploadedFileLocation) throws Exception {
    try {
        writeToFile(zipStream, uploadedFileLocation);
        FileUtils.forceDelete(new File(uploadedFileLocation));
        } catch (Exception e) {
             throw e;
        }
}


private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) {
    try {
        OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
        int read = 0;
        byte[] bytes = new byte[1024];

        out = new FileOutputStream(new File(uploadedFileLocation));
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
        uploadedInputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

When I send a file to my server, it cannot get deleted. When using FileUtils.forceDelete(), it says that it cannot delete the file. I can delete the file manually while the server is still running after it tries to delete the file with file utils. Why can't it just delete it itself?! any ideas? Thanks

EDIT: Could the issue be that the InputStream from the POST is alive until the POST returns? So, even when I call to delete the file, the stream is still kept alive by the POST? Is this even possible?


回答1:


In my limited windows experience it can be one of the two things

I would check 1) THe anti-virus software is trying to scan the file 2) Some kind of indexer (System or custom) is trying to index the file.

you can use a tool like processExplorer to see which process holding up the file descriptor. http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx



来源:https://stackoverflow.com/questions/17979638/cant-delete-file-after-it-gets-written

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!