KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > teamkonzept > web > TKTemporaryFile


1 /*
2  * $Header: /cvsroot/webman-cms/source/webman/com/teamkonzept/web/TKTemporaryFile.java,v 1.8 2002/01/18 15:24:11 mischa Exp $
3  *
4  */

5 package com.teamkonzept.web;
6
7 import java.io.*;
8 import java.util.*;
9 import org.apache.log4j.Category;
10
11 public class TKTemporaryFile
12 {
13
14     private static final Category CATEGORY = Category.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     {
21         if (tempFileDirectory == null) {
22             tempFileDirectory = createTempDir();
23         }
24         return newTempFile( tempFileDirectory );
25     }
26     
27     private static File newTempFile(File baseDir)
28     {
29         File newFile = null;
30         while( newFile == null ) {
31             String JavaDoc nameBase = String.valueOf( rand.nextLong() );
32             newFile = new File( baseDir, nameBase+".tmp" );
33             if( newFile.exists() ) {
34                 newFile = null;
35             }
36         }
37         return newFile;
38     }
39     
40     private static File createTempDir() throws FileNotFoundException
41     {
42         String JavaDoc dirname = System.getProperty ("java.io.tmpdir");
43         File tempDir = new File(dirname);
44         if(!tempDir.exists()) {
45             tempDir.mkdirs();
46         }
47         else if (!tempDir.isDirectory()) {
48             throw new FileNotFoundException("Unable to create temporary directory " + tempDir.getName() +
49                 " Reason: A file with the same name already exists.");
50         }
51         return tempDir;
52     }
53     
54     {
55         try {
56             tempFileDirectory = createTempDir();
57         }
58         catch (FileNotFoundException e) {
59             CATEGORY.error("Cannot create temp directory " + System.getProperty("java.io.tmpdir"));
60         }
61     }
62 }
63
64
Popular Tags