[英]Not able to Close and delete already opened .xls file thro' java code
我正在嘗試通過Java代碼刪除目錄,現在的用例是:如果文件已經打開,則應首先將其關閉,然后我可以直接刪除目錄。
我試圖使用FileoutputStream關閉文件,但無法創建FileoutputStream對象,它顯示錯誤,例如“該進程無法訪問該文件,因為該文件正在被另一個進程使用”
還有另一種方法可以幫助我嗎?
如果您要刪除的文件已由Java應用程序使用Runtime.getRuntime()。exec()方法或任何其他方式打開,則必須先關閉該文件,然后才能執行任務。 當然,由於該文件已打開,因此您也無法刪除該文件的主文件夾(目錄),因此需要首先關閉該文件。 這是完全有意義的操作系統保護措施,為什么我們要刪除其他人正在使用的內容?
為了關閉文件,您將需要知道正在使用該文件的進程的名稱,例如,如果已使用MS Windows NotePad.exe打開了名為MyText.txt的文本文件,則必須關閉該文件 。使文件MyText.txt保持打開狀態。
下面,我提供了一種簡單的方法,只要您提供正確的進程名稱,它就可以為您關閉一個開放的外部進程。 在上面的示例中,這將是“ Notepad.exe”
public static void killProcess(String processName) {
// PLEASE NOTE: This method will currently Kill "ALL"
// open processes of the supplied process
// name unless commented code changes are
// made.
try {
Runtime rt = Runtime.getRuntime();
// For Windows OS...
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
rt.exec("taskkill /T /F /IM " + processName);
//rt.exec("taskkill /T /F /PID " + Long.parseLong(processName)); // Supply the PID value as string
//rt.exec("taskkill /F /FI \"WINDOWTITLE eq " + processName + "\" /T"); // Supply the window title bar text.
// If you want to kill only a single instance of the
// named process then get its PID value and use:
// "taskkill /T /F /PID PID_Value" OR you can provide
// the window title and use:
// "taskkill /F /FI \"WINDOWTITLE eq " + processName + "\" /T"
}
// For OSX And Linux OS's...
else {
rt.exec("sudo killall -9 '" + processName + "'");
//rt.exec("kill -9 " + Long.parseLong(processName)); // Supply the PID value as string
// If you want to kill only a single instance of the
// named process then get its PID value and use:
// "kill -9 PID_Value"
}
rt.freeMemory();
}
catch (IOException | SecurityException | IllegalArgumentException ex) {
ex.printStackTrace();
}
}
在此方法代碼開頭的注釋狀態中,將終止所有當前正在運行且具有提供的進程名稱的進程。 如果您只想終止某個進程的特定實例,例如上面的示例,並且您有四個Notepad.exe實例可以打開來編輯其他文本文件,那么您需要將方法代碼更改為:
rt.exec("taskkill /F /FI \"WINDOWTITLE eq " + processName + "\" /T");
代替這個:
rt.exec("taskkill /T /F /IM " + processName);
當然,您可以將此方法稱為:
killProcess("MyText.txt - Notepad");
您在其中提供應用程序的窗口標題欄中的內容。 一旦上述方法完成,您就可以刪除MyText.txt文件及其所在的文件夾,因為它不再被使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.