1 package org.robolectric.util; 2 3 import java.io.IOException; 4 import java.nio.file.FileAlreadyExistsException; 5 import java.nio.file.FileVisitResult; 6 import java.nio.file.Files; 7 import java.nio.file.Path; 8 import java.nio.file.SimpleFileVisitor; 9 import java.nio.file.attribute.BasicFileAttributes; 10 11 public class TempDirectory { 12 private final Path basePath; 13 TempDirectory(String name)14 public TempDirectory(String name) { 15 try { 16 basePath = Files.createTempDirectory("robolectric-" + name); 17 } catch (IOException e) { 18 throw new RuntimeException(e); 19 } 20 21 // Use a manual hook that actually clears the directory 22 // This is necessary because File.deleteOnExit won't delete non empty directories 23 Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { 24 @Override public void run() { 25 destroy(); 26 } 27 })); 28 } 29 create(String name)30 public Path create(String name) { 31 Path path = basePath.resolve(name); 32 try { 33 Files.createDirectory(path); 34 } catch (IOException e) { 35 throw new RuntimeException(e); 36 } 37 return path; 38 } 39 createIfNotExists(String name)40 public Path createIfNotExists(String name) { 41 Path path = basePath.resolve(name); 42 try { 43 Files.createDirectory(path); 44 } catch (FileAlreadyExistsException e) { 45 // that's ok 46 return path; 47 } catch (IOException e) { 48 throw new RuntimeException(e); 49 } 50 return path; 51 } 52 destroy()53 public void destroy() { 54 try { 55 clearDirectory(basePath); 56 Files.delete(basePath); 57 } catch (IOException ignored) { 58 } 59 } 60 clearDirectory(final Path directory)61 private void clearDirectory(final Path directory) throws IOException { 62 Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { 63 @Override 64 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { 65 Files.delete(file); 66 return FileVisitResult.CONTINUE; 67 } 68 69 @Override 70 public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { 71 if (!dir.equals(directory)) { 72 Files.delete(dir); 73 } 74 return FileVisitResult.CONTINUE; 75 } 76 }); 77 } 78 } 79