| 1 | package de.uka.ipd.sdq.sensorframework.tests.util; |
| 2 | |
| 3 | // |
| 4 | // TempDir.java |
| 5 | // |
| 6 | import java.io.File; |
| 7 | import java.io.FileWriter; |
| 8 | import java.io.IOException; |
| 9 | |
| 10 | public class TempDir |
| 11 | { |
| 12 | private static DirDeleter deleterThread; |
| 13 | |
| 14 | static |
| 15 | { |
| 16 | deleterThread = new DirDeleter(); |
| 17 | Runtime.getRuntime().addShutdownHook(deleterThread); |
| 18 | } |
| 19 | |
| 20 | /** |
| 21 | * Creates a temp directory with a generated name (given a certain prefix) in a given directory. |
| 22 | * The directory (and all its content) will be destroyed on exit. |
| 23 | */ |
| 24 | public static File createGeneratedName(String prefix) |
| 25 | throws IOException |
| 26 | { |
| 27 | return createGeneratedName(prefix, null); |
| 28 | } |
| 29 | |
| 30 | /** |
| 31 | * Creates a temp directory with a generated name (given a certain prefix) in a given directory. |
| 32 | * The directory (and all its content) will be destroyed on exit. |
| 33 | */ |
| 34 | public static File createGeneratedName(String prefix, File directory) |
| 35 | throws IOException |
| 36 | { |
| 37 | File tempFile = File.createTempFile(prefix, "", directory); |
| 38 | if (!tempFile.delete()) |
| 39 | throw new IOException(); |
| 40 | if (!tempFile.mkdir()) |
| 41 | throw new IOException(); |
| 42 | deleterThread.add(tempFile); |
| 43 | return tempFile; |
| 44 | } |
| 45 | /** |
| 46 | * Creates a temp directory with a given name in a given directory. |
| 47 | * The directory (and all its content) will be destroyed on exit. |
| 48 | */ |
| 49 | public static File createNamed(String name, File directory) |
| 50 | throws IOException |
| 51 | { |
| 52 | File tempFile = new File(directory, name); |
| 53 | if (!tempFile.mkdir()) |
| 54 | throw new IOException(); |
| 55 | deleterThread.add(tempFile); |
| 56 | return tempFile; |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * For testing purposes TODO make this a proper test |
| 61 | */ |
| 62 | public static void main(String[] args) |
| 63 | { |
| 64 | try |
| 65 | { |
| 66 | int serial = 123; |
| 67 | // create a temp directory with a given name in c:\\project root-directory |
| 68 | File tempDir = TempDir.createNamed(""+serial, new File("c:\\project"));//TODO tststs |
| 69 | // create an empty file in the temp directory. |
| 70 | File f = new File(tempDir, "hello.txt"); |
| 71 | FileWriter fw = new FileWriter(f); |
| 72 | fw.write("hello"); |
| 73 | fw.close(); |
| 74 | System.out.println("Temp dir created is " + tempDir.getPath()); |
| 75 | System.out.println("Temp dir (and all its content) will be deleted on exit"); |
| 76 | } |
| 77 | catch (Exception e) |
| 78 | { |
| 79 | e.printStackTrace(); |
| 80 | } |
| 81 | } |
| 82 | } |