1
我的上傳servlet不斷拋出一個異常,說我試圖替換的文件(接近我的代碼的末尾)無法從(看似)隨機刪除。我不知道是什麼原因造成的,因爲我沒有使用任何流,並且該文件沒有在我的瀏覽器中打開。有誰知道這可能是什麼原因造成的?我完全無能爲力,因爲代碼對我來說似乎是正確的。這是我第一次使用DiskFileItem,所以我不確定是否有細微處理。使用DiskFileItem時,爲什麼會出現非確定性文件刪除錯誤?
請記住,它有時起作用,有時不起作用。我迷失了。
問題區域:
File destination = new File(wellnessDir + File.separator + fileName + ".pdf");
System.out.println("destination file exists: " + destination.exists());
System.out.println("file to be moved exists: " + uploadedFile.exists());
if(destination.exists()){
boolean deleted = destination.delete();
if(!deleted)
throw new Exception("Could not delete file at " + destination);
}
我的系統中出局總是說,這兩個文件和目標存在。我試圖讓上傳覆蓋現有的文件。
全碼:(& pastebin)
private void uploadRequestHandler(ServletFileUpload upload, HttpServletRequest request)
{
// Handle the request
String fileName = "blank";
try{
List items = upload.parseRequest(request);
//Process the uploaded items
Iterator iter = items.iterator();
File uploadedFile = new File(getHome() + File.separator + "temp");
if(uploadedFile.exists()){
boolean tempDeleted = uploadedFile.delete();
if(!tempDeleted)
throw new Exception("Existing temp file could not be deleted.");
}
//write the file
while (iter.hasNext()) {
DiskFileItem item = (DiskFileItem) iter.next();
if(item.isFormField()){
String fieldName = item.getFieldName();
String fieldValue = item.getString();
if(fieldName.equals("fileName"))
fileName = fieldValue;
//other form values would need to be handled here, right now only need for fileName
}else{
item.write(uploadedFile);
}
}
if(fileName.equals("blank"))
throw new Exception("File name could not be parsed.");
//move file
File wellnessDir = new File(getHome() + File.separator + "medcottage" + File.separator + "wellness");
File destination = new File(wellnessDir + File.separator + fileName + ".pdf");
System.out.println("destination file exists: " + destination.exists());
System.out.println("file to be moved exists: " + uploadedFile.exists());
if(destination.exists()){
boolean deleted = destination.delete();
if(!deleted)
throw new Exception("Could not delete file at " + destination);
}
FileUtil.move(uploadedFile, new File(wellnessDir + File.separator + fileName + ".pdf"));
writeResponse();
} catch (Exception e) {
System.out.println("Error handling upload request.");
e.printStackTrace();
}
}
編輯:添加,getHome()和 「家」 並不是真正的代碼,這只是爲了保護我的主路徑
你使用的是Windows還是Linux? –
我正在使用Windows。 – buddyp450
你在Windows上打開了索引嗎?有時它開始索引新的目錄,所以它們不能被刪除。嘗試關閉索引,看看是否改善了事情。 –