有沒有在Java應用程序內部建立臨時目錄的標準可靠方法? Java的問題數據庫中有一個條目,註釋中包含一些代碼,可是我想知道在一個經常使用的庫(Apache Commons等)中是否找到標準解決方案? java
這是我決定爲本身的代碼執行的操做: 數據庫
/** * Create a new temporary directory. Use something like * {@link #recursiveDelete(File)} to clean this directory up since it isn't * deleted automatically * @return the new directory * @throws IOException if there is an error creating the temporary directory */ public static File createTempDir() throws IOException { final File sysTempDir = new File(System.getProperty("java.io.tmpdir")); File newTempDir; final int maxAttempts = 9; int attemptCount = 0; do { attemptCount++; if(attemptCount > maxAttempts) { throw new IOException( "The highly improbable has occurred! Failed to " + "create a unique temporary directory after " + maxAttempts + " attempts."); } String dirName = UUID.randomUUID().toString(); newTempDir = new File(sysTempDir, dirName); } while(newTempDir.exists()); if(newTempDir.mkdirs()) { return newTempDir; } else { throw new IOException( "Failed to create temp dir named " + newTempDir.getAbsolutePath()); } } /** * Recursively delete file or directory * @param fileOrDir * the file or dir to delete * @return * true iff all files are successfully deleted */ public static boolean recursiveDelete(File fileOrDir) { if(fileOrDir.isDirectory()) { // recursively delete contents for(File innerFile: fileOrDir.listFiles()) { if(!FileUtilities.recursiveDelete(innerFile)) { return false; } } } return fileOrDir.delete(); }
我遇到了一樣的問題,因此這只是對那些有興趣的人的另外一個答案,它與上述之一類似: apache
public static final String tempDir = System.getProperty("java.io.tmpdir")+"tmp"+System.nanoTime(); static { File f = new File(tempDir); if(!f.exists()) f.mkdir(); }
對於個人應用程序,我決定添加一個選項來清除退出時的溫度 ,所以我添加了一個關閉掛鉤: 安全
Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { //stackless deletion String root = MainWindow.tempDir; Stack<String> dirStack = new Stack<String>(); dirStack.push(root); while(!dirStack.empty()) { String dir = dirStack.pop(); File f = new File(dir); if(f.listFiles().length==0) f.delete(); else { dirStack.push(dir); for(File ff: f.listFiles()) { if(ff.isFile()) ff.delete(); else if(ff.isDirectory()) dirStack.push(ff.getPath()); } } } } });
該方法在刪除temp以前先刪除全部子目錄和文件,而不使用調用棧(這是徹底可選的,此時您可使用遞歸進行此操做),可是我想保持安全。 服務器
即便之後顯式刪除它,也不要使用deleteOnExit()
。 app
谷歌「 deleteonexit是邪惡的」以得到更多信息,可是問題的要點是: less
deleteOnExit()
僅在正常JVM關閉時刪除,而不會崩潰或殺死JVM進程。 dom
deleteOnExit()
僅在JVM關閉時刪除-對於長時間運行的服務器進程來講很差,由於: ide
最deleteOnExit()
消耗每一個臨時文件條目的內存。 若是您的進程運行了幾個月,或者在很短的時間內建立了許多臨時文件,則您將消耗內存,而且在JVM關閉以前永遠不要釋放內存。 this
正如您在其餘答案中看到的那樣,沒有標準的方法出現。 所以,您已經提到了Apache Commons,我提出了使用Apache Commons IO中的 FileUtils的如下方法:
/** * Creates a temporary subdirectory in the standard temporary directory. * This will be automatically deleted upon exit. * * @param prefix * the prefix used to create the directory, completed by a * current timestamp. Use for instance your application's name * @return the directory */ public static File createTempDirectory(String prefix) { final File tmp = new File(FileUtils.getTempDirectory().getAbsolutePath() + "/" + prefix + System.currentTimeMillis()); tmp.mkdir(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { FileUtils.deleteDirectory(tmp); } catch (IOException e) { e.printStackTrace(); } } }); return tmp; }
這是首選,由於apache commons是最接近要求的「標準」的庫,而且可與JDK 7和更早版本一塊兒使用。 這還會返回一個「舊」 File實例(基於流),而不是一個「 new」 Path實例(基於緩衝區,這是JDK7的getTemporaryDirectory()方法的結果)->所以,它返回大多數人在須要時他們想建立一個臨時目錄。
好吧,「 createTempFile」實際上建立了文件。 那麼,爲何不先刪除它,而後再對其執行mkdir呢?