Java 使用FileOutputStream写入后无法删除文件
我有一个RESTfulWeb服务,它有一个上传文件的功能。它工作正常,但我的问题是,当我尝试在Windows中手动删除上传的文件时,它表示该文件已被使用 要删除这些文件,我需要停止Glassfish服务器。我担心的是内存使用,当用户持续上传大量文件时,这段非托管代码可能会导致一些问题。我已经关闭了Java 使用FileOutputStream写入后无法删除文件,java,rest,web-services,inputstream,fileoutputstream,Java,Rest,Web Services,Inputstream,Fileoutputstream,我有一个RESTfulWeb服务,它有一个上传文件的功能。它工作正常,但我的问题是,当我尝试在Windows中手动删除上传的文件时,它表示该文件已被使用 要删除这些文件,我需要停止Glassfish服务器。我担心的是内存使用,当用户持续上传大量文件时,这段非托管代码可能会导致一些问题。我已经关闭了InputStream和FileOutputStream变量。请看下面的代码,我不知道我遗漏了什么 @POST @Path("upload") @Consumes(MediaType.MULTIPART
InputStream
和FileOutputStream
变量。请看下面的代码,我不知道我遗漏了什么
@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
两次:一旦发生第二次赋值,第一个创建的流将作为非引用对象保留在内存中,直到发生垃圾回收。由于服务器未停止,并且可能内存负载不太高,垃圾收集器也不收集垃圾,因此无法从Windows中删除垃圾。您必须在最后关闭块中的流,或者(最好是)关闭流在try with resources
语句中使用它们。我尝试过,结果相同。然后您可以发布更新的代码吗?在尝试删除之前,您需要关闭FileOutputStream
@德米特里约波夫的建议只会让事情变得更糟。。这很尴尬。这就是为什么不建议使用复制粘贴。是,我现在可以删除文件,一旦我删除第二次初始化。非常感谢你。