【发布时间】:2015-07-15 03:39:48
【问题描述】:
我先放我的代码:
@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();
}
}
当我将文件发送到我的服务器时,它无法被删除。使用FileUtils.forceDelete() 时,表示无法删除该文件。在服务器尝试使用文件实用程序删除文件后,我可以在服务器仍在运行时手动删除文件。为什么不能自己删除?!有任何想法吗?谢谢
编辑:问题可能是来自 POST 的 InputStream 在 POST 返回之前还存在吗?那么,即使我调用删除文件,POST 仍然使流保持活动状态?这甚至可能吗?
【问题讨论】:
-
文件可能存在权限问题?
-
我注意到有时在关闭文件然后立即尝试访问它们时有时会在某些机器上导致奇怪的行为,例如防病毒软件会在您打开文件一毫秒后执行某些操作关闭它。我知道这是一个糟糕的长期解决方案,但请查看在尝试删除之前添加睡眠是否可以解决问题。
-
问题可能是来自 POST 的 InputStream 在 POST 返回之前一直存在吗?那么,即使我调用删除文件,POST 仍然使流保持活动状态?这甚至可能吗?
-
@StephenD 为什么要实例化两次?是错字吗?
-
文件创建后为什么要立即删除?
标签: java file inputstream delete-file