import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * Create a uniquely named temporary file.
 *
 * @param near if null, the temporary file will be created in the current directory.
 * If near is a valid file, then the temporary file will be created in the
 * same directory as near.
 * If near represents a file, the temporary file will be created in the
 * same directory as near.
 * If near represents a directory, the temporary file will be created in that
 * directory.
 * If near is invalid, then the temporary file will be created in the current
 * directory.
 * @param prefix name of application to prefix to file name.
 * @return a temporary File with a unique name of the form ~xxxxx99999999.temp.
 */
static File getTempFile ( File near, String prefix ) throws IOException {
   String path = null;
   if ( near != null )
      if ( near.isFile() ) path = near.getParent();
      else if ( near.isDirectory() ) path = near.getPath();

   Random wheel = new Random(); // seeded from the clock
   File tempFile = null;
   do
      {
      // generate random a number 10,000,000 .. 99,999,999
      int unique = ( wheel.nextInt() & Integer. MAX_VALUE ) %90000000 + 10000000;
      tempFile = new File( path, '~' + prefix + Integer.toString ( unique) + ".temp" );
      } while ( tempFile.exists() );
   // We "finally" found a name not already used. Nearly always the first time.
   // Quickly stake our claim to it by opening/closing it to create it.
   // In theory somebody could have grabbed it in that tiny window since
   // we checked if it exists, but that is highly unlikely.
   new FileOutputStream( tempFile ).close();

   // debugging peek at the name generated.
   if ( false )
      {
      out.println( tempFile.getCanonicalPath());
      }
   return tempFile;
} // end getTempFile