1 package be
.nikiroo
.utils
;
3 import java
.io
.Closeable
;
5 import java
.io
.IOException
;
8 * A small utility class to generate auto-delete temporary files in a
9 * centralised location.
13 public class TempFiles
implements Closeable
{
17 * Create a new {@link TempFiles} -- each instance is separate and have a
18 * dedicated sub-directory in a shared temporary root.
20 * The whole repository will be deleted on close (if you fail to call it,
21 * the program will <b>try</b> to all it on JVM termination).
24 * the instance name (will be <b>part</b> of the final directory
28 * in case of I/O error
30 public TempFiles(String name
) throws IOException
{
31 root
= File
.createTempFile(".temp", "");
32 IOUtils
.deltree(root
, true);
34 root
= new File(root
.getParentFile(), ".temp");
37 throw new IOException("Cannot create root directory: " + root
);
42 root
= createTempFile(name
);
43 IOUtils
.deltree(root
, true);
47 throw new IOException("Cannot create root subdirectory: " + root
);
52 * Create an auto-delete temporary file.
55 * a base for the final filename (only a <b>part</b> of said
58 * @return the newly created file
61 * in case of I/O errors
63 public synchronized File
createTempFile(String name
) throws IOException
{
65 while (name
.length() < 3) {
70 File tmp
= File
.createTempFile(name
, "");
71 IOUtils
.deltree(tmp
, true);
73 File test
= new File(root
, tmp
.getName());
77 throw new IOException("Cannot create temporary file: "
88 * Create an auto-delete temporary directory.
90 * Note that creating 2 temporary directories with the same name will result
91 * in two <b>different</b> directories, even if the final name is the same
92 * (the absolute path will be different).
95 * the actual directory name (not path)
97 * @return the newly created file
100 * in case of I/O errors, or if the name was a path instead of a
103 public synchronized File
createTempDir(String name
) throws IOException
{
104 File localRoot
= createTempFile(name
);
105 IOUtils
.deltree(localRoot
, true);
108 if (!localRoot
.exists()) {
109 throw new IOException("Cannot create subdirectory: " + localRoot
);
112 File dir
= new File(localRoot
, name
);
113 if (!dir
.getName().equals(name
)) {
114 throw new IOException(
115 "Cannot create temporary directory with a path, only names are allowed: "
123 throw new IOException("Cannot create subdirectory: " + dir
);
130 public synchronized void close() throws IOException
{
131 IOUtils
.deltree(root
); // NO exception here
132 root
.getParentFile().delete(); // only if empty
136 protected void finalize() throws Throwable
{