01: /*
02: * $Header: /cvsroot/webman-cms/source/webman/com/teamkonzept/web/TKTemporaryFile.java,v 1.8 2002/01/18 15:24:11 mischa Exp $
03: *
04: */
05: package com.teamkonzept.web;
06:
07: import java.io.*;
08: import java.util.*;
09: import org.apache.log4j.Category;
10:
11: public class TKTemporaryFile {
12:
13: private static final Category CATEGORY = Category
14: .getInstance(TKTemporaryFile.class);
15:
16: private static Random rand = new Random();
17: private static File tempFileDirectory = null;
18:
19: public static File newTempFile() throws FileNotFoundException {
20: if (tempFileDirectory == null) {
21: tempFileDirectory = createTempDir();
22: }
23: return newTempFile(tempFileDirectory);
24: }
25:
26: private static File newTempFile(File baseDir) {
27: File newFile = null;
28: while (newFile == null) {
29: String nameBase = String.valueOf(rand.nextLong());
30: newFile = new File(baseDir, nameBase + ".tmp");
31: if (newFile.exists()) {
32: newFile = null;
33: }
34: }
35: return newFile;
36: }
37:
38: private static File createTempDir() throws FileNotFoundException {
39: String dirname = System.getProperty("java.io.tmpdir");
40: File tempDir = new File(dirname);
41: if (!tempDir.exists()) {
42: tempDir.mkdirs();
43: } else if (!tempDir.isDirectory()) {
44: throw new FileNotFoundException(
45: "Unable to create temporary directory "
46: + tempDir.getName()
47: + " Reason: A file with the same name already exists.");
48: }
49: return tempDir;
50: }
51:
52: {
53: try {
54: tempFileDirectory = createTempDir();
55: } catch (FileNotFoundException e) {
56: CATEGORY.error("Cannot create temp directory "
57: + System.getProperty("java.io.tmpdir"));
58: }
59: }
60: }
|