/** * Returns a new fresh folder with a random name under the temporary * folder. */ public File newFolder() throws IOException { try { File tempDir = createTempDir(getRoot()); addSourceInfo(tempDir); return tempDir; } catch (IllegalStateException e) { throw new IOException(e.getMessage()); // IOException(e) not available prior to 1.6 } }
@Override protected void after() { if (folder != null) { delete(); folder = null; initialized = false; } }
protected File createFreshTempDir() { try { return temporaryFolder.newFolder(); } catch (IOException e) { throw new AssertionError(e); } }
protected File createTempDir() { if (temporaryFolder != null && temporaryFolder.isInitialized()) { try { return temporaryFolder.newFolder(); } catch (IOException e) { throw new RuntimeIOException(e); } } return com.google.common.io.Files.createTempDir(); }
/** * Returns a new fresh file with a random name under the temporary folder. */ public File newFile() throws IOException { return File.createTempFile("junit", null, getRoot()); }
/** * Delete all files and folders under the temporary folder. * Usually not called directly, since it is automatically applied * by the {@link Rule} */ public void delete() { recursiveDelete(folder); }
/** * @return the location of this temporary folder. */ public File getRoot() { if (folder == null) { try { create(); } catch(IOException e) { throw new IllegalStateException("the temporary folder could not be created", e); } } return folder; }
protected void cleanUpTmpFolder(File tempDir) { if (temporaryFolder == null || !temporaryFolder.isInitialized()) { try { tempDir.deleteOnExit(); // Classloader needs .class files to lazy load an anonymous non static classes Files.cleanFolder(tempDir, new FileFilter() { @Override public boolean accept(File pathname) { boolean isClass = pathname.getName().endsWith(".class"); if(isClass) { pathname.deleteOnExit(); } return !isClass; } }, true, true); } catch (FileNotFoundException e) { // ignore } } }
/** * Same signature as {@link java.io.File#createTempFile(String, String)}. */ public File createTempFile(String prefix, String suffix) throws IOException { return File.createTempFile(prefix, prefix, getRoot()); }
private void recursiveDelete(File file) { File[] files= file.listFiles(); if (files != null) for (File each : files) recursiveDelete(each); file.delete(); } }
/** * Returns a new fresh file with the given name under the temporary folder. */ public File newFile(String fileName) throws IOException { File file= new File(getRoot(), fileName); file.createNewFile(); return file; }
/** * Returns a new fresh folder with the given name under the temporary folder. */ public File newFolder(String... folderNames) { File file = getRoot(); for (String folderName : folderNames) { file = new File(file, folderName); file.mkdir(); } return file; }