我首先把我的代碼:無法刪除文件時,它是一個爭論
@Post
public Representation post(InputStream zip) throws Throwable {
createFile(zip, "C:/temp\abc.zip");
return new StringRepresentation("File uploaded");
}
public void createFile(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();
}
}
我試圖做一個服務器,它允許用戶上載的zip文件。服務器然後將zip文件寫入磁盤,解壓縮,然後刪除zip,同時將解壓縮的部分保留在服務器上。但是,當我將zip文件發送到我的服務器時,它不能被刪除。當使用FileUtils.forceDelete()
時,它說它不能刪除該文件。解壓縮之後,該zip是理想的刪除操作。
編輯:我只能在post(InputStream zip)
返回後刪除文件。如果我從post
方法中調用delete,它將不會被刪除,因爲post沒有返回。有沒有解決的辦法?
對不起,我accidentily省略它。現在有一個文件名。 'C:/ temp/abc.zip' –
在這種情況下,我仍然傾向於雙重初始化的輸出流,該輸出流可能會將該位置的文件保持爲打開狀態,直到對象退出堆棧。 我並不熟悉FileUtils庫,但我知道'java.io.File'類確實有它自己的刪除函數。也許如果第一個方法不起作用,請嘗試'new File(fileUploadLocation).delete()'。 此外,當它失敗時,你會得到一個異常消息嗎?如果是這樣,你可以將它添加到你的文章? – Deactivator2
原來我應該調用'file.delete();'而不是使用'FileUtils'。 –