View Javadoc

1   package http.utils.multipartrequest;
2   
3   import java.io.File;
4   import java.io.FileWriter;
5   import java.util.Random;
6   import java.io.IOException;
7   
8   /***
9   	Borrowed pretty much all the the logic from java.io.File (Java 2)
10  */
11  public class TempFile
12  {
13  	/* -- Temporary files -- */
14      private static final Object tmpFileLock = new Object();
15      private static int counter = -1; /* Protected by tmpFileLock */
16  
17  	/***
18  		@param prefix		Must be at least 3 characters long
19  		@param suffix		The file extension (minus the extension)
20  		@param directory	Where do you want this temporary file saved.
21  	*/
22      public static File createTempFile(String prefix, String suffix, File directory) throws IOException
23      {
24  		if (prefix == null) throw new NullPointerException();
25  		if (prefix.length() < 3)
26  	    	throw new IllegalArgumentException("Prefix string too short");
27  
28          String extension = (suffix == null) ? "tmp" : suffix;
29  		synchronized(tmpFileLock)
30  		{
31  		    SecurityManager sm = System.getSecurityManager();
32  		    File f;
33  	    	while(true)
34  			{
35  				f = generateFile(prefix, extension, directory);
36  				if(!f.exists())
37  				{
38  					// Create the file.
39  					FileWriter writer = new FileWriter(f);
40  					writer.close();
41  					break;//break out of while loop!
42  				}
43              }
44  		    return f;
45  		}
46      }
47  
48  	/***
49  		This method is used to generate the file name.
50  	*/
51      private static File generateFile(String prefix, String extension, File dir) throws IOException
52      {
53  		if (counter == -1)
54  		    counter = new Random().nextInt() & 0xffff;
55  		counter++;
56  
57  		return new File(dir, prefix + Integer.toString(counter) + "."+extension);
58      }
59  }